查找具有最接近整数值的文档

查找具有最接近整数值的文档

本文介绍了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-查找具有最接近整数值的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:38
查看更多