MongoDB聚合操作中如何将浮点数截断为1或2位小数?
average Field to 1 or 2 Decimal Places in MongoDB Aggregation Hey there! Looking at your existing aggregation query, you're already doing a solid job calculating the average IMDB rating for each cast member. To truncate that average value to 1 or 2 decimal places, you can use MongoDB's $trunc aggregation operator (which cuts off extra decimals without rounding). If you prefer rounding instead of strict truncation, swap it out for $round—let's break down both options.
Truncate to 1 Decimal Place
Modify the $group stage of your query to wrap the $avg calculation with $trunc, specifying 1 as the number of decimal places to keep:
db.movies.aggregate([ { $match: { languages: "English", cast: { $exists: true } } }, { $unwind: "$cast" }, { $group: { _id: "$cast", numFilms: { $sum: 1 }, average: { $trunc: [ { $avg: "$imdb.rating" }, 1 ] } } }, { $sort: { numFilms: -1 } }, { $limit: 1 } ])
With this adjustment, your output will be:
{ "_id" : "John Wayne", "numFilms" : 107, "average" : 6.4 }
Truncate to 2 Decimal Places
Just tweak the second parameter in $trunc to 2 to retain two decimal places:
db.movies.aggregate([ { $match: { languages: "English", cast: { $exists: true } } }, { $unwind: "$cast" }, { $group: { _id: "$cast", numFilms: { $sum: 1 }, average: { $trunc: [ { $avg: "$imdb.rating" }, 2 ] } } }, { $sort: { numFilms: -1 } }, { $limit: 1 } ])
This will return:
{ "_id" : "John Wayne", "numFilms" : 107, "average" : 6.42 }
Rounding Instead of Truncation
If you want to round the value (rather than just cutting off decimals), replace $trunc with $round using the same syntax. For your current average value of 6.424..., rounding to 2 decimals would still give 6.42, but if the average was 6.426, it would round up to 6.43.
Quick Syntax Notes
- Both
$truncand$roundtake two arguments: the numeric value to process, and the number of decimal places to retain. $truncstrictly removes extra decimals without adjusting the remaining digits, while$roundadjusts based on standard rounding rules.
内容的提问来源于stack exchange,提问作者Rahul Raj

