$round
The `$round` operator is used to round a number to a specified decimal place. It's useful in aggregations where numerical precision is important, such as financial calculations or statistical analysis.
Syntax
{ $round: [ <number>, <place> ] }
Parameters
<number>
stringrequiredThe number to be rounded.
<place>
stringrequiredThe decimal place to which the number should be rounded.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"location": { "lat": -89.2384, "lon": -46.4012 },
"sales": { "totalSales": 75670 }
}
Round the location coordinates of stores
Round the latitude and longitude coordinates to one decimal place.
Query:
db.stores.aggregate([
{ $match: { company: { $in: ["First Up Consultants"] } } },
{
$project: {
company: 1,
"location.lat": 1,
"location.lon": 1,
roundedLat: { $round: ["$location.lat", 1] },
roundedLon: { $round: ["$location.lon", 1] }
}
}
])
Output:
[
{
"_id": "39acb3aa-f350-41cb-9279-9e34c004415a",
"location": { "lat": 87.2239, "lon": -129.0506 },
"company": "First Up Consultants",
"roundedLat": 87.2,
"roundedLon": -129.1
}
]
Round to the nearest thousand
Round the total sales volume to the nearest thousand using negative decimal place.
Query:
db.stores.aggregate([
{ $match: { company: { $in: ["First Up Consultants"] } } },
{
$project: {
company: 1,
"sales.totalSales": 1,
roundedSales: { $round: ["$sales.totalSales", -3] }
}
}
])
Output:
[
{
"_id": "39acb3aa-f350-41cb-9279-9e34c004415a",
"sales": {},
"company": "First Up Consultants",
"roundedSales": 279000
}
]