Arithmetic Aggregation Operators in MongoDB

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

OperatorPurposeExample
$addAdds numbers{ $add: [10, 20] } → 30
$subtractSubtracts one number from another{ $subtract: [20, 10] } → 10
$multiplyMultiplies numbers{ $multiply: [10, 5] } → 50
$divideDivides one number by another{ $divide: [20, 5] } → 4
$modReturns remainder{ $mod: [17, 5] } → 2
$powCalculates power{ $pow: [2, 4] } → 16
$sqrtCalculates square root{ $sqrt: 25 } → 5
$ceilRounds up to nearest integer{ $ceil: 12.3 } → 13
$floorRounds down to nearest integer{ $floor: 12.8 } → 12
$truncRemoves decimal portion{ $trunc: 15.89 } → 15
$absReturns 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.

By admin