mongodb - 查找最接近整数值的文档 [英] mongodb - Find document with closest integer value

查看:34
本文介绍了mongodb - 查找最接近整数值的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文档集合,其中的 ratio 属性是一个浮点数.

Let's assume I have a collection with documents with a ratio attribute that is a floating point number.

{'ratio':1.437}

如何编写查询以查找与给定整数值最接近的单个文档,而不使用驱动程序将它们全部加载到内存中并找到具有最小值 abs(x-ratio)?

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:

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 最接近目标整数.

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

MongoDB 3.2 更新

3.2 版本增加了对 $abs 绝对值聚合运算符,现在允许在单个 aggregate 查询中完成此操作:

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}
])

这篇关于mongodb - 查找最接近整数值的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆