该 $round
运算符用于将数字舍入到指定的小数位。 它在数值精度非常重要的聚合中非常有用,例如财务计算或统计分析。
语法
{ $round: [ <number>, <place> ] }
参数
参数 | 说明 |
---|---|
<number> |
要舍入的数字。 |
<place> |
数字应舍入到的小数位数。 |
示例
舍入纬度和经度值
db.collection.aggregate([
{
$project: {
roundedLat: { $round: ["$location.lat", 1] },
roundedLon: { $round: ["$location.lon", 1] }
}
}
])
这将纬度和经度值舍入到一个小数位,以提高可读性:
[
{ "_id": 1, "location": { "lat": 37.774929, "lon": -122.419416 }, "roundedLat": 37.8, "roundedLon": -122.4 },
{ "_id": 2, "location": { "lat": 40.712776, "lon": -74.005974 }, "roundedLat": 40.7, "roundedLon": -74.0 }
]
将总销售额舍入到最接近的千
db.collection.aggregate([
{
$project: {
roundedSales: { $round: ["$sales.fullSales", -3] }
}
}
])
这会将总销售额舍入到最接近的千位,这对于财务报告很有用:
[
{ "_id": 3, "sales": { "fullSales": 25400 }, "roundedSales": 25000 },
{ "_id": 4, "sales": { "fullSales": 127500 }, "roundedSales": 128000 }
]
将折扣百分比舍入为最接近的整数
db.collection.aggregate([
{
$unwind: "$promotionEvents"
},
{
$unwind: "$promotionEvents.discounts"
},
{
$project: {
eventName: "$promotionEvents.eventName",
categoryName: "$promotionEvents.discounts.categoryName",
roundedDiscount: { $round: ["$promotionEvents.discounts.discountPercentage", 0] }
}
}
])
这会将折扣百分比舍入为最接近的整数,这有助于显示和定价调整:
[
{
"_id": 5,
"eventName": "Black Friday",
"categoryName": "Electronics",
"roundedDiscount": 20
},
{
"_id": 6,
"eventName": "Holiday Sale",
"categoryName": "Clothing",
"roundedDiscount": 15
}
]