Arithmetic Operators
Do math — add, subtract, multiply, divide, and get absolute values.
← Previous | Index | Next: 10 - Comparison Operators →
Arithmetic operators take numeric values as input and return a single numeric result.
$add and $subtract
Compute the sum or difference of values. $add accepts two or more arguments.
// Syntax
{ $add: [<expr1>, <expr2>, ...] }
{ $subtract: [<expr1>, <expr2>] }Example: Sum multiple research fields
db.subprojects.aggregate([
{
$project: {
researchFocus: {
$add: [
"$theoreticalResearch",
"$focusResearch",
"$appliedResearch"
]
}
}
},
{ $out: "subprojectReport" }
]);Example: Subtract a fixed value
{
value: { $subtract: ["$projectFunding", 10] }
}$multiply
Computes the product of two or more values.
{ $multiply: [<expr1>, <expr2>, ...] }$divide
Divides the first value by the second.
{ $divide: [<expr1>, <expr2>] }$abs
Returns the absolute value of a number.
{ $abs: <expression> }Example
db.projects.aggregate([
{
$project: {
projectFunding: { $abs: "$projectFunding" },
title: 1
}
},
{ $out: "projectReport" }
]);Nesting Arithmetic Expressions
The real power comes from combining operators:
// (3 + 3) × 10 = 60
{ $multiply: [{ $add: [3, 3] }, 10] }
// (4 + 4) / (2 × 3) = 1.33...
{
$divide: [
{ $add: [4, 4] },
{ $multiply: [2, 3] }
]
}Full pipeline example
db.projects.aggregate([
{
$addFields: {
projectFunding: {
$multiply: [
{ $add: ["$projectFunding", 10] },
3
]
}
}
},
{ $out: "projectReport" }
]);