1

I run MongoDB 2.4.4-pre- under Linux. I've got a table with elements each of which has a field named "num". This field contains a positive integer. What have my query to look like to find the element, which "num" field contains the nearest even number to the number, I'd like to inspect?

Community
  • 1
  • 1
JustLogin
  • 1,822
  • 5
  • 28
  • 50
  • What range would be considered near? – Sammaye Jun 19 '13 at 13:04
  • No range. I just need to find the nearest one. – JustLogin Jun 19 '13 at 13:14
  • See: http://stackoverflow.com/questions/13275491/mongodb-find-document-with-closest-integer-value – James Wahlin Jun 19 '13 at 13:24
  • Some more detail in your question may be necessary: How many documents are in the collection? How often is the query performed? Is the collection changing frequently? Is the `num` field indexed? Could you change the schema to include whether the `num` is an even number (add `isEven` for example)? – WiredPrairie Jun 19 '13 at 13:41

1 Answers1

3

The linked related question describes two approaches in finding the "nearest" value. One is to run two queries: to find nearest value higher than given number, and to find nearest lower value. The other approach is to use geospatial index (which would require changing your schema).

If you don't mind two queries then the only modification you need to make on the query is to add a constraint that you only want to consider even numbers:

  db.collection.find ( { "num" : { "$mod" : [ 2, 0 ] } } )

is a way to query for only numbers which are even (see $mod operator docs).

Your two queries then become:

a=db.collection.find({"num":{"$mod":[2,0], $gte:INPUTNUM }}).sort({"num":1}).limit(-1)
b=db.collection.find({"num":{"$mod":[2,0], $lte:INPUTNUM }}).sort({"num":-1}).limit(-1)

where you keep from a, b the one that's closest to INPUTNUM.

Community
  • 1
  • 1
Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133