Let’s assume I have a collection with documents with a ratio attribute that is a floating point number.
{'ratio':1.437}
How do I write a query to find the single document with the closest value to a given integer without loading them all into memory using a driver and finding one with the smallest value of abs(x-ratio)?
Interesting problem. I don’t know if you can do it in a single query, but you can do it in two:
Then you just check which of the two docs has the
ratioclosest to the target integer.MongoDB 3.2 Update
The 3.2 release adds support for the
$absabsolute value aggregation operator which now allows this to be done in a singleaggregatequery: