MongoDB - How to truncate a number to 3 decimal places

I do not know how to round a number in MongoDB. I only find how to do this with 2 decimal places, but not with more decimal places.

"location" : {
    "type" : "Point",
    "coordinates" : [ 
        -74.00568, 
        40.70511
    ]
}

This is an example of the coordinate that I need to round with three numbers after the dot. Thanks you

+4
source share
1 answer

For 3rd decimal rounding you can use this formula.

$divide: [ {$trunc: { $multiply: [ "$$coordinate" , 1000 ] } }, 1000 ]

For example, with your sample data and using this aggregation:

db.getCollection('Test2').aggregate([
    { $project : 
        { 
            "location.type" : "$location.type",
            "location.coordinates" :  
            { 
                $map: 
                {
                    input: "$location.coordinates",
                    as: "coordinate",
                    in: { $divide: [ {$trunc: { $multiply: [ "$$coordinate" , 1000 ] } }, 1000 ] }
              }
            }   
        } 
    }
])

You can get the desired result.

{
    "_id" : ObjectId("59f9a4c814167b414f6eb553"),
    "location" : {
        "type" : "Point",
        "coordinates" : [ 
            -74.005, 
            40.705
        ]
    }
}
+1
source

Source: https://habr.com/ru/post/1688466/


All Articles