2

Given the following MongoDB documents...

{ "_id" : ObjectId("55e67b28010000880ca4c043"), "amount" : { "value" : 1.125, "currency" : "USD" } }
{ "_id" : ObjectId("55e897e60100009f0051da48"), "amount" : { "value" : 1.525, "currency" : "USD" } }
{ "_id" : ObjectId("55ea1b520100006d004e602a"), "amount" : { "value" : 1.825, "currency" : "USD" } }

How do I get the document with amount.value closest to 2.0 (1.825 in this case)? For instance, I need to create a query that takes a number as the input and returns the document with amount.value closest to the specified number.

j3d
  • 9,492
  • 22
  • 88
  • 172
  • 1
    and if you have the value 2.1 what you want to return ? – Rohit Jain Oct 01 '15 at 06:30
  • Still 1.825... I need to find the closest number, regardless of whether the given number is less or greater. – j3d Oct 01 '15 at 07:30
  • Will you flexible to change the value to "value" : [1.125,0] ? – Rohit Jain Oct 01 '15 at 07:38
  • 1
    That's a bit difficult since such a change would affect a lot of code... what's the second number for? – j3d Oct 01 '15 at 07:49
  • MongoDB supports geolocation index, which will support $near, but if you are not comfortable you can go with ans given by Nishant below – Rohit Jain Oct 01 '15 at 07:53
  • Let me give a look... – j3d Oct 01 '15 at 07:55
  • Possible duplicate of [mongodb - Find document with closest integer value](http://stackoverflow.com/questions/13275491/mongodb-find-document-with-closest-integer-value) and worth noting that every response here is based on the content in the answers provided there. – Blakes Seven Oct 02 '15 at 02:36

1 Answers1

3

You can accomplish it in two queries.

providedValue = 1.34;

closestBelow = db.test.find({
    "amount.value": {
    $lte: providedValue
    }
}).sort({
    amount.value: -1
}).limit(1);

closestAbove = db.test.find({
    "amount.value": {
    $gte: providedValue
    }
}).sort({
    amount.value: 1
}).limit(1);

You can check this link, for further details mongodb - Find document with closest integer value

Community
  • 1
  • 1
Nishant
  • 3,614
  • 1
  • 20
  • 26
  • I am thinking about wether this can be achieved through a linked list created with an aggregation or sth. Would save a query during runtime... – Markus W Mahlberg Oct 01 '15 at 08:12