Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - How to Truncate Float Values to One or Two decimal points in aggregate?

Let's say this is the query:

db.movies.aggregate([
  {$match: {languages: "English", cast:{$exists:true}}},

  {$unwind: "$cast"},

  {$group: {_id: "$cast", numFilms:{$sum: 1}, average:{$avg: "$imdb.rating"}   
  }},

  {$sort: {numFilms:-1}},

  {$limit: 1}
])

And I get the output:

{ "_id" : "John Wayne", "numFilms" : 107, "average" : 6.424299065420561 }

How can I truncate average to single/double decimal points? I wanted to see an output like this:

{ "_id" : "John Wayne", "numFilms" : 107, "average" : 6.42 }

I tried this post, but seems like I can't get away doing the same with $avg operator. How can I achieve this?

Potential duplicate

I believe the above linked isn't a duplicate, because mine deals with $avg operator.

like image 986
Rahul Raj Avatar asked Jan 01 '26 13:01

Rahul Raj


1 Answers

You can achieve this with a $project stage with a $trunc but $multiply before and $divide after to deal with the decimal places.

For example if we add the following:

db.test.insertMany([{
    number: 123.456
}, {
    number: 456.789
}, {
    number: 123
}]);

We can run an aggregation with the following:

db.test.aggregate([{
    $project: {
        number: {
            $divide: [{
                $trunc: {
                    $multiply: ["$number", 100]
                }
            }, 100]
        }
    }
}])

Which will give us:

{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f3"), "number" : 123.45 }
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f4"), "number" : 456.78 }
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f5"), "number" : 123 }
like image 126
Kevin Smith Avatar answered Jan 03 '26 02:01

Kevin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!