MongoDB:如何在查询中获得 N 个小数精度 [英] MongoDB: How to get N decimals precision in a query
本文介绍了MongoDB:如何在查询中获得 N 个小数精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定 MongoDB 集合中的以下文档...
Given the following documents in a MongoDB collection...
{ "_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 }}
...是否可以选择 amount
为 1.12 的所有文档(即在查询中获得 2 位小数精度)?
... is it possible to select all those documents where amount
is 1.12 (i.e. get 2 decimals precision in the query)?
推荐答案
您可以使用 $where
运算符.
You can do this with the $where
operator.
db.collection.find({ "$where": function() {
return Math.round(this.amount.value * 100)/ 100 === 1.12;
}
})
<小时>
编辑(在此评论之后)
在这种情况下,您应该使用聚合框架,尤其是 $redact
运算符,这比使用 $where
In this case you should use the aggregation framework especially the $redact
operator and this is much faster than the solution using $where
db.collection.aggregate([
{ "$redact": {
"$cond": [
{ "$eq": [
{ "$subtract": [
"$amount.value",
{ "$mod": [ "$amount.value", 0.01 ] }
]},
0.03
]},
"$$KEEP",
"$$PRUNE"
]
}}
])
这篇关于MongoDB:如何在查询中获得 N 个小数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文