MongoDB: How to get N decimals precision in a query

前端 未结 4 798
庸人自扰
庸人自扰 2021-01-25 04:58

Given the following documents in a MongoDB collection...

{ \"_id\": 1, \"amount\": { \"value\": 1.123456789999, \"rate\": 1.2 }}
{ \"_id\": 2, \"amount\": { \"va         


        
4条回答
  •  礼貌的吻别
    2021-01-25 05:18

    You can do this with the $where operator.

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

    EDIT (after this comment)

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

提交回复
热议问题