MongoDB $round Operator

What You'll Learn
The MongoDB $round operator rounds a number to a specified decimal place in aggregation pipelines. Syntax: { $round: [ <number>, <place> ] }. The place parameter ranges from -20 to 100, and defaults to 0 (nearest integer).
Master 6 production-ready examples — from basic syntax to decimal place control, aggregation pipeline integration, analytics with $group + $avg, a complete comparison of $round vs $trunc vs $ceil vs $floor, and real-world Indian use cases (GST invoices, salary calculations, dashboard metrics).
⚡ Quick Reference — $round Syntax
// Syntax:
{ $round: [ <number>, <place> ] }
// Quick Examples:
{ $round: "$price" } // → integer
{ $round: [ "$price", 0 ] } // → integer
{ $round: [ "$price", 2 ] } // → 2 decimals
{ $round: [ "$price", -2 ] } // → nearest 100
{ $round: [ { $avg: "$price" }, 1 ]} // → 1 decimal
// Banker's Rounding: 2.5 → 2, 3.5 → 4
// Available since MongoDB 4.2ExpressionAggregation operator
v4.2August 2019
-20 to 100Default: 0
Banker'sHalf to even
⚠️ Banker's Rounding (Round Half to Even)
MongoDB's $round uses banker's rounding — when a value is exactly halfway, it rounds to the nearest even number, not always up!
This reduces cumulative rounding bias in large datasets — it's the standard in banking and finance.
Example 1: Basic $round Syntax
The $round operator rounds a number to a specified decimal place. It takes an array with two elements: the number expression and the decimal place (optional, defaults to 0).
// Basic $round (default: round to integer)
db.products.aggregate([
{
$project: {
name: 1,
originalPrice: "$price",
roundedPrice: { $round: "$price" }
}
}
])
// $round with Array Format
db.products.aggregate([
{
$project: {
name: 1,
roundedTo0: { $round: [ "$price", 0 ] },
roundedTo1: { $round: [ "$price", 1 ] },
roundedTo2: { $round: [ "$price", 2 ] }
}
}
])Example 2: Rounding to Different Decimal Places
The $round operator's place parameter can be positive (decimal places), zero (integer), or negative (tens, hundreds, thousands).
// Negative Place: Round to Tens, Hundreds
db.transactions.aggregate([
{
$project: {
item: 1,
original: "$amount",
nearest10: { $round: [ "$amount", -1 ] },
nearest100: { $round: [ "$amount", -2 ] },
nearest1000: { $round: [ "$amount", -3 ] }
}
}
])Example 3: $round in Aggregation Pipeline
Use $round within $project, $addFields, and $set stages for production-ready queries.
// Calculate Order Total with GST
db.orders.aggregate([
{
$addFields: {
subtotal: {
$round: [
{ $reduce: {
input: "$items",
initialValue: 0,
in: { $add: [
"$$value",
{ $multiply: ["$$this.price", "$$this.qty"] }
] }
} },
2
]
}
}
},
{
$addFields: {
totalWithGST: {
$round: [
{ $multiply: [ "$subtotal", 1.18 ] },
2
]
}
}
}
])Example 4: $round with $group and $avg
Combine $round with $group and accumulator operators for analytics dashboards.
// Category-wise Average Price
db.sales.aggregate([
{
$group: {
_id: "$category",
avgPrice: { $avg: "$price" },
avgRating: { $avg: "$rating" },
totalRevenue: { $sum: "$price" },
count: { $sum: 1 }
}
},
{
$project: {
category: "$_id",
avgPrice: { $round: [ "$avgPrice", 2 ] },
avgRating: { $round: [ "$avgRating", 1 ] },
totalRevenue: 1,
count: 1
}
},
{ $sort: { totalRevenue: -1 } }
])Example 5: $round vs $trunc vs $ceil vs $floor
MongoDB provides four rounding operators. Understanding the differences is crucial for financial calculations and reporting.
db.comparison.aggregate([
{
$project: {
input: { $literal: 23.567 },
round: { $round: [ 23.567, 0 ] }, // 24
trunc: { $trunc: [ 23.567, 0 ] }, // 23
ceil: { $ceil: 23.567 }, // 24
floor: { $floor: 23.567 } // 23
}
}
])
// Banker's Rounding (round half to even):
// $round: [ 2.5, 0 ] → 2 (not 3!)
// $round: [ 3.5, 0 ] → 4
// $round: [ 4.5, 0 ] → 4 (not 5!)Example 6: Real-World GST & Salary Calculations
Production-ready pipelines for Indian e-commerce pricing with GST and salary management.
// Payroll: Salary with Deductions
db.employees.aggregate([
{
$project: {
name: 1,
monthlyGross: {
$round: [
{ $divide: [ "$annualCTC", 12 ] },
0
]
},
basicPay: {
$round: [
{ $divide: [
{ $multiply: [ "$annualCTC", 0.4 ] },
12
] },
0
]
},
pfDeduction: {
$round: [
{ $divide: [
{ $multiply: [ "$annualCTC", 0.048 ] },
12
] },
0
]
}
}
}
])📝 Key Takeaways:
- •
{ $round: [ "$field", 2 ] }— rounds to 2 decimal places. Default place is 0. - • Negative places round to tens (-1), hundreds (-2), thousands (-3). Range: -20 to 100.
- • Banker's rounding: halfway values (2.5, 4.5) round to nearest EVEN number.
- • Use
$roundfor general rounding,$ceilfor shipping (always up),$truncfor age (towards zero),$floorfor conservative estimates. - • Round at the final stage, not intermediate steps — intermediate rounding causes cumulative errors!
✅ Best Practices & Common Mistakes
Do's
- ✅ Round at the LAST stage, not intermediate
- ✅ Use place: 2 for currency/financial values
- ✅ Use negative place for dashboard summaries
- ✅ Use $ceil for shipping/pagination math
- ✅ Test with halfway values (2.5, 3.5, 4.5)
- ✅ Use $ifNull before $round for null safety
- ✅ Store exact values, round only for display
Don'ts
- ❌ Don't round in every pipeline stage
- ❌ Don't assume 2.5 rounds to 3 (it's 2!)
- ❌ Don't use $round inside $group
- ❌ Don't confuse $round with $trunc
- ❌ Don't use $ceil/$floor when $round suffices
- ❌ Don't forget null/NaN handling
- ❌ Don't use $round before MongoDB 4.2
❓ Frequently Asked Questions
Explore More MongoDB Operators!
Learn $trunc, $ceil, $floor, $avg, $sum, and other aggregation pipeline operators with interactive examples.
12 people found this page helpful
