MongoDB: How to get N decimals precision in a query

前端 未结 4 799
庸人自扰
庸人自扰 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:04

    Starting from the answer I got from user3100115, here below is the final soluton:

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

    I hope it helps.

    0 讨论(0)
  • 2021-01-25 05:11

    you can just use the regex operator

    db.test.find({ value: { $regex: 1\.12[0-9]*}})
    
    0 讨论(0)
  • 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"
            ]
         }}
    ])
    
    0 讨论(0)
  • 2021-01-25 05:29

    You're effectively doing a range query where 1.12 <= value < 1.13, so you could do this as:

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

    Which is a truncation to 2 decimal places. If you want to round it, you'd be looking for 1.115 <= value < 1.125:

    db.test.find({'amount.value': {$gte: 1.115, $lt: 1.125}})
    
    0 讨论(0)
提交回复
热议问题