Mongo has a $near
query operator, which "[s]pecifies a point for which a geospatial query returns the documents from nearest to farthest."
Is there an equivalent for integers? That is, say I have a collection of documents with amount
fields, which are integers. I want to get the documents in order of the amounts closes to a given amount.
For example, say I have this collection (mongo shell):
> db.foob.find({}, {amount: 1, _id: 0})
{ "amount" : 10 }
{ "amount" : 20 }
{ "amount" : 50 }
{ "amount" : 100 }
{ "amount" : 1000 }
{ "amount" : 1100 }
{ "amount" : 1300 }
I want something like this:
> db.foob.find({}, {amount: 1, _id: 0}).sortByClosestTo({amount: 400})
{ "amount" : 100 }
{ "amount" : 50 }
{ "amount" : 20 }
{ "amount" : 10 }
{ "amount" : 1000 }
{ "amount" : 1100 }
{ "amount" : 1300 }
If there is no built-in query operator for this, is there any way to accomplish this sort short of getting the entire collection and doing a .sort(key=lambda doc: abs(doc['amount'] - n)
?