MongoDB: How to get N decimals precision in a query

前端 未结 4 859
庸人自扰
庸人自扰 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: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}})
    

提交回复
热议问题