Abdel DOOFENSCHMIRTZ
Abdel DOOFENSCHMIRTZ

Reputation: 83

How to truncate a number to 3 decimals

I do not know how to round a number in MongoDB. I only find how to do it with 2 decimals but not with more decimals.

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

These is an example of a coordinate that I need to round with 3 numbers after the dot. Thank you

Upvotes: 8

Views: 4260

Answers (3)

adhg
adhg

Reputation: 10903

With coordinates (as you have it in an array) you can trunc them in 2 steps:

  1. $arrayElemAt
  2. $trunc

to put it in motion:

 {'$project':{ 
    'lat': {'$trunc': [{ '$arrayElemAt': [ "$location.coordinates", 0 ] },2]},
    'lon': {'$trunc': [{ '$arrayElemAt': [ "$location.coordinates", 1 ] },2]}, 
 },

I assume your first value in the coordinates is the latitude.

Upvotes: 0

Xavier Guihot
Xavier Guihot

Reputation: 61766

Starting Mongo 4.2, there is a new $trunc aggregation operator which can be used to truncate a number to a specified decimal place:

{ $trunc : [ <number>, <place> ] }

Which can be used as such within an aggregation pipeline (here we truncate xs to 3 decimal places):

// db.collection.insert([{x: 1.23456}, {x: -9.87654}, {x: 0.055543}, {x: 12.9999}])
db.collection.aggregate([{ $project: { "trunc_x": { $trunc: ["$x", 3] }}}])
// [{"trunc_x": 1.234}, {"trunc_x": -9.876}, {"trunc_x": 0.055}, {"trunc_x": 12.999}]

Note that the place parameter is optional, and omitting it results in truncating to a whole integer (i.e. truncating at 0 decimal places).

Also note the equivalent $round operator if you're interested in rounding rather than truncating.

Upvotes: 1

Serkan Arslan
Serkan Arslan

Reputation: 13403

For 3 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 obtain the desired result.

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

Upvotes: 7

Related Questions