MongoDB: 如何在查询中获得 N 位小数精度

MongoDB: How to get N decimals precision in a query

给定 MongoDB 集合中的以下文档...

{ "_id": 1, "amount": { "value": 1.123456789999, "rate": 1.2 }}
{ "_id": 2, "amount": { "value": 2.9844, "rate": 1.2 }}
{ "_id": 3, "amount": { "value": 1.123876, "rate": 1.2 }}
{ "_id": 4, "amount": { "value": 3.3557886, "rate": 1.2 }}
{ "_id": 5, "amount": { "value": 1.12599976, "rate": 1.2 }}

... 是否可以 select 所有 amount1.12 的文档(即在查询中获得 2 位小数精度)?

您可以使用 $where 运算符执行此操作。

db.collection.find({ "$where": function() { 
    return Math.round(this.amount.value * 100)/ 100 === 1.12; 
    }
})

编辑(在 this comment 之后)

在这种情况下,您应该使用聚合框架,尤其是 $redact 运算符,这比使用 $where

的解决方案快得多
db.collection.aggregate([
    { "$redact": { 
        "$cond": [
            { "$eq": [
                { "$subtract": [ 
                    "$amount.value", 
                    { "$mod": [ "$amount.value",  0.01 ] }
                ]}, 
                0.03
            ]}, 
            "$$KEEP", 
            "$$PRUNE"
        ]
     }}
])

您实际上是在 1.12 <= value < 1.13 处执行范围查询,因此您可以这样做:

db.test.find({'amount.value': {$gte: 1.12, $lt: 1.13}})

截断到小数点后两位。如果你想四舍五入,你会寻找 1.115 <= value < 1.125:

db.test.find({'amount.value': {$gte: 1.115, $lt: 1.125}})

您可以只使用正则表达式运算符

db.test.find({ value: { $regex: 1\.12[0-9]*}})

从我在user3100115得到的答案出发,下面是最终的解决方案:

db.orders.find({ "$where": function() { return this.amount.value - (this.amount.value % 0.01) === 0.03; }})

希望对您有所帮助。