Arithmetic aggregation operators are used to perform mathematical calculations on numeric values in MongoDB aggregation pipelines. They are commonly used with stages such as $project, $addFields, and $group.
They are commonly used with stages such as $project, $set, $addFields, and $group.
Common Arithmetic Aggregation Operators
| Operator | Purpose | Example |
|---|---|---|
$add | Adds numbers | { $add: [10, 20] } → 30 |
$subtract | Subtracts one number from another | { $subtract: [20, 10] } → 10 |
$multiply | Multiplies numbers | { $multiply: [10, 5] } → 50 |
$divide | Divides one number by another | { $divide: [20, 5] } → 4 |
$mod | Returns remainder | { $mod: [17, 5] } → 2 |
$pow | Calculates power | { $pow: [2, 4] } → 16 |
$sqrt | Calculates square root | { $sqrt: 25 } → 5 |
$ceil | Rounds up to nearest integer | { $ceil: 12.3 } → 13 |
$floor | Rounds down to nearest integer | { $floor: 12.8 } → 12 |
$trunc | Removes decimal portion | { $trunc: 15.89 } → 15 |
$abs | Returns absolute value | { $abs: -25 } → 25 |
Example
Suppose we have:
db.emp.insertMany([
{ empnm: "Mital", salary: 25000, bonus: 5000 },
{ empnm: "Rahul", salary: 30000, bonus: 7000 }
])
1. $add — Addition
db.emp.aggregate([
{
$project: {
empnm: 1,
total: { $add: ["$salary", "$bonus"] }
}
}
])
Output:
Mital 30000
Rahul 37000
2. $subtract — Subtraction
db.emp.aggregate([
{
$project: {
empnm: 1,
salaryAfter: { $subtract: ["$salary", "$bonus"] }
}
}
])
3. $multiply — Multiplication
db.emp.aggregate([
{
$project: {
empnm: 1,
doubleSalary: { $multiply: ["$salary", 2] }
}
}
])
4. $divide — Division
db.emp.aggregate([
{
$project: {
empnm: 1,
halfSalary: { $divide: ["$salary", 2] }
}
}
])
5. $mod — Remainder
db.emp.aggregate([
{
$project: {
result: { $mod: [17, 5] }
}
}
])
Output:
2
6. $pow — Power
db.emp.aggregate([
{
$project: {
result: { $pow: [2, 4] }
}
}
])
Output:
16
In short
Arithmetic aggregation operators allow MongoDB to perform mathematical calculations directly inside an aggregation pipeline, reducing the need to calculate values in application code.