假设我有一个文档集合,其比率属性是浮点数。
{'ratio':1.437}
如何编写一个查询来查找与给定整数最接近的值的单个文档,而不使用驱动程序将它们全部加载到内存中并找到具有最小值的文档abs(x-ratio)
?
有趣的问题。我不知道你是否可以在单个查询中完成它,但你可以在两个查询中完成它:
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);
然后你只需检查两个文档中哪一个有ratio
最接近目标整数。
MongoDB 3.2 更新
3.2 版本增加了对$abs https://docs.mongodb.org/manual/reference/operator/aggregation/abs/#abs-aggregation绝对值聚合运算符现在允许在单个中完成此操作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}
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)