mongodb - Find document with closest integer value

老子叫甜甜 提交于 2019-11-27 05:04:11

Interesting problem. I don't know if you can do it in a single query, but you can do it in two:

var x = 1; // given integer
closestBelow = db.test.find({ratio: {$lte: x}}).sort({ratio: -1}).limit(1);
closestAbove = db.test.find({ratio: {$gt: x}}).sort({ratio: 1}).limit(1);

Then you just check which of the two docs has the ratio closest to the target integer.

MongoDB 3.2 Update

The 3.2 release adds support for the $abs absolute value aggregation operator which now allows this to be done in a single aggregate query:

var x = 1;
db.test.aggregate([
    // Project a diff field that's the absolute difference along with the original doc.
    {$project: {diff: {$abs: {$subtract: [x, '$ratio']}}, doc: '$$ROOT'}},
    // Order the docs by diff
    {$sort: {diff: 1}},
    // Take the first one
    {$limit: 1}
])

I have another idea, but very tricky and need to change your data structure.

You can use geolocation index which supported by mongodb

First, change your data to this structure and keep the second value with 0

{'ratio':[1.437, 0]}

Then you can use $near operator to find the the closest ratio value, and because the operator return a list sorted by distance with the integer you give, you have to use limit to get only the closest value.

db.places.find( { ratio : { $near : [50,0] } } ).limit(1)

If you don't want to do this, I think you can just use @JohnnyHK's answer :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!