MongoDB Aggregation Operators

What you’ll learn
- What MongoDB aggregation operators are and where they run in pipelines.
- How operators differ from accumulators and query filters.
- Operator families: arithmetic, comparison, logical, array, string, date, and type conversion.
- A suggested learning path from
$addthrough$cond. - Links to every operator tutorial on CodeToFun (136 operators).
Prerequisites
Basic MongoDB and aggregation familiarity: find(), the $match stage, and field paths like "$amount". Complete the installation guide if you have not set up mongosh yet.
- Pipeline stages: operators most often appear inside
$projectand$addFields. - Expression syntax:
{ $add: [ "$a", "$b" ] }— operator name as key, arguments in an array or object. - Null handling: many operators return
nullwhen any operand is null—pair with$ifNull. - Next step: after operators, study accumulators for per-group rollups in
$group.
Key concepts
Aggregation operators are building blocks for computed fields. Each operator takes inputs (field paths, literals, or nested expressions) and returns one value per document.
Per-document
Unlike accumulators, operators never span multiple documents unless nested inside $map or $reduce.
Composable
Nest operators freely: $round on a $divide result inside $cond.
$expr in $match
Use comparison operators in filters: { $match: { $expr: { $gte: [ "$score", 80 ] } } }.
136 tutorials
One page per operator at /mongodb/operators/{slug}.
Overview
Operators power transformations in aggregation: line totals, discount flags, formatted dates, trimmed labels, filtered tag arrays, and conditional tiers. They are the expression language inside stages—not separate pipeline steps.
Arithmetic
$add, $multiply, $round, $mod.
Strings & arrays
$concat, $split, $filter, $map.
Dates & logic
$dateAdd, $dateToString, $cond, $eq.
⚖️ Picking the right operator
Match the task to the operator family before you write an expression.
| Goal | Start with | Notes |
|---|---|---|
| Line total or sum fields | $add / $multiply | Chain in one expression or use multiple computed fields. |
| Handle missing values | $ifNull | Replace null before math or concatenation. |
| Conditional column | $cond or $switch | Ternary vs multi-branch logic. |
| Compare field values | $eq, $gte | Use inside $expr for computed filters. |
| Format dates in reports | $dateToString | Control format with format and timezone. |
| Filter array elements | $filter | Keep items matching a sub-expression. |
| Totals per group | $sum accumulator | Not an operator—runs inside $group. |
Multiple operators in one $addFields
Compute subtotal, apply a discount flag, and format the order date—four operators, one stage.
db.orders.aggregate([
{ $match: { status: "completed" } },
{
$addFields: {
subtotal: { $multiply: ["$quantity", "$unitPrice"] },
discountApplied: {
$cond: {
if: { $gte: ["$quantity", 10] },
then: true,
else: false
}
},
orderLabel: {
$concat: ["Order #", { $toString: "$orderId" }]
},
orderMonth: {
$dateToString: { format: "%Y-%m", date: "$createdAt" }
}
}
},
{ $limit: 5 }
]); Suggested learning path
Work through tutorials in this order if you are new to aggregation operators.
- Math:
$add,$subtract,$multiply,$divide. - Nulls & logic:
$ifNull,$cond,$and,$or. - Compare:
$eq,$gtewith$exprin$match. - Strings:
$concat,$toUpper,$trim. - Arrays:
$filter,$map,$size. - Dates:
$dateToString,$dateAdd,$dateDiff. - Then accumulators:
$sumand$avginside$group.
The sidebar tutorial order walks every operator alphabetically by slug, starting with $abs.
Operator index
Every tutorial lives at /mongodb/operators/{slug}. Operator names use collapsed lowercase slugs (for example dateadd for $dateAdd, arrayelemat for $arrayElemAt).
Arithmetic & math
| Operator | What it does |
|---|---|
$add | Add numbers or milliseconds to a date. |
$subtract | Subtract numbers or compute date differences. |
$multiply | Multiply numeric expressions together. |
$divide | Divide one number by another. |
$mod | Return the remainder after division. |
$abs | Absolute value of a number. |
$ceil | Round a number up to the nearest integer. |
$floor | Round a number down to the nearest integer. |
$round | Round to nearest integer with optional decimal places. |
$trunc | Truncate toward zero (drop fractional part). |
$sqrt | Square root of a non-negative number. |
$pow | Raise a number to an exponent. |
$exp | Euler's number e raised to a power. |
$ln | Natural logarithm (base e). |
$log | Logarithm of a number in a given base. |
$log10 | Base-10 logarithm. |
$rand | Random float from 0 to 1 (non-deterministic). |
Trigonometry
| Operator | What it does |
|---|---|
$sin | $sin trigonometric function. |
$cos | $cos trigonometric function. |
$tan | $tan trigonometric function. |
$asin | $asin trigonometric function. |
$acos | $acos trigonometric function. |
$atan | $atan trigonometric function. |
$atan2 | $atan2 trigonometric function. |
$sinh | $sinh trigonometric function. |
$cosh | $cosh trigonometric function. |
$tanh | $tanh trigonometric function. |
$asinh | $asinh trigonometric function. |
$acosh | $acosh trigonometric function. |
$atanh | $atanh trigonometric function. |
$degreesToRadians | $degreesToRadians aggregation expression for $project and $addFields. |
$radiansToDegrees | $radiansToDegrees aggregation expression for $project and $addFields. |
Comparison
| Operator | What it does |
|---|---|
$cmp | Three-way compare: returns -1, 0, or 1. |
$eq | True when two values are equal. |
$ne | True when two values are not equal. |
$gt | True when first value is greater. |
$gte | True when first value is greater or equal. |
$lt | True when first value is less. |
$lte | True when first value is less or equal. |
Logical & conditional
| Operator | What it does |
|---|---|
$and | True when every argument is true. |
$or | True when any argument is true. |
$not | Logical negation of a boolean expression. |
$nor | True when no argument is true. |
$cond | If-then-else conditional expression. |
$switch | Multi-branch conditional (like switch/case). |
$ifNull | Replace null or missing with a fallback value. |
Arrays
| Operator | What it does |
|---|---|
$arrayElemAt | Return the element at a zero-based array index. |
$concatArrays | Concatenate multiple arrays into one. |
$filter | Keep array elements that match a condition. |
$indexOfArray | $indexOfArray aggregation expression for $project and $addFields. |
$indexOfBytes | $indexOfBytes aggregation expression for $project and $addFields. |
$indexOfCP | $indexOfCP aggregation expression for $project and $addFields. |
$isArray | $isArray aggregation expression for $project and $addFields. |
$map | Apply an expression to each array element. |
$range | $range aggregation expression for $project and $addFields. |
$reduce | Fold an array into a single accumulated value. |
$reverseArray | $reverseArray aggregation expression for $project and $addFields. |
$size | Count elements in an array. |
$slice | Return a sub-array by index range. |
$sortArray | $sortArray aggregation expression for $project and $addFields. |
$zip | $zip aggregation expression for $project and $addFields. |
$allElementsTrue | $allElementsTrue aggregation expression for $project and $addFields. |
$anyElementTrue | $anyElementTrue aggregation expression for $project and $addFields. |
$arrayToObject | $arrayToObject aggregation expression for $project and $addFields. |
$objectToArray | $objectToArray aggregation expression for $project and $addFields. |
$in | True when a value exists in an array. |
Sets
| Operator | What it does |
|---|---|
$setDifference | $setDifference set operation on arrays. |
$setEquals | $setEquals set operation on arrays. |
$setIntersection | $setIntersection set operation on arrays. |
$setIsSubset | $setIsSubset set operation on arrays. |
$setUnion | $setUnion set operation on arrays. |
$setField | $setField set operation on arrays. |
Strings & regex
| Operator | What it does |
|---|---|
$concat | Join strings into one value. |
$strcasecmp | $strcasecmp aggregation expression for $project and $addFields. |
$strlenBytes | $strlenBytes aggregation expression for $project and $addFields. |
$strLenCP | $strLenCP aggregation expression for $project and $addFields. |
$substr | $substr aggregation expression for $project and $addFields. |
$substrBytes | $substrBytes aggregation expression for $project and $addFields. |
$substrCP | $substrCP aggregation expression for $project and $addFields. |
$toLower | Convert string to lowercase. |
$toUpper | Convert string to uppercase. |
$trim | Remove leading and trailing whitespace. |
$ltrim | $ltrim aggregation expression for $project and $addFields. |
$rtrim | $rtrim aggregation expression for $project and $addFields. |
$split | Split a string into an array by delimiter. |
$regex | $regex string pattern matching. |
$regexFind | $regexFind string pattern matching. |
$regexFindAll | $regexFindAll string pattern matching. |
$regexMatch | $regexMatch string pattern matching. |
Date & time
| Operator | What it does |
|---|---|
$dateAdd | Add units (day, month, etc.) to a date. |
$dateDiff | Difference between two dates in chosen units. |
$dateFromParts | $dateFromParts date/time expression for pipelines. |
$dateFromString | $dateFromString date/time expression for pipelines. |
$dateSubtract | $dateSubtract date/time expression for pipelines. |
$dateToParts | $dateToParts date/time expression for pipelines. |
$dateToString | Format a date field as a string. |
$dateTrunc | $dateTrunc date/time expression for pipelines. |
$dayOfMonth | $dayOfMonth date/time expression for pipelines. |
$dayOfWeek | $dayOfWeek date/time expression for pipelines. |
$dayOfYear | $dayOfYear date/time expression for pipelines. |
$hour | $hour date/time expression for pipelines. |
$isoDayOfWeek | $isoDayOfWeek date/time expression for pipelines. |
$isoWeek | $isoWeek date/time expression for pipelines. |
$isoWeekYear | $isoWeekYear date/time expression for pipelines. |
$millisecond | $millisecond date/time expression for pipelines. |
$minute | $minute date/time expression for pipelines. |
$month | $month date/time expression for pipelines. |
$second | $second date/time expression for pipelines. |
$week | $week date/time expression for pipelines. |
$year | $year date/time expression for pipelines. |
Type conversion
| Operator | What it does |
|---|---|
$convert | Convert a value to a specified BSON type. |
$toBool | Convert input to Bool type. |
$toDate | Convert input to Date type. |
$toDecimal | Convert input to Decimal type. |
$toDouble | Convert input to Double type. |
$toInt | Convert input to Int type. |
$toLong | Convert input to Long type. |
$toObjectId | Convert input to ObjectId type. |
$toString | Convert input to String type. |
$type | Return the BSON type of a value as a number. |
$isNumber | $isNumber aggregation expression for $project and $addFields. |
Document, query & misc
| Operator | What it does |
|---|---|
$binarySize | $binarySize aggregation expression for $project and $addFields. |
$bsonSize | $bsonSize aggregation expression for $project and $addFields. |
$comment | $comment aggregation expression for $project and $addFields. |
$exists | Match documents where a field exists or is missing. |
$expr | Use aggregation expressions inside query filters. |
$function | $function aggregation expression for $project and $addFields. |
$getField | $getField aggregation expression for $project and $addFields. |
$jsonSchema | $jsonSchema aggregation expression for $project and $addFields. |
$let | Define variables for use in sub-expressions. |
$literal | Return a constant value without field-path parsing. |
$meta | $meta aggregation expression for $project and $addFields. |
$nin | $nin aggregation expression for $project and $addFields. |
$sampleRate | $sampleRate aggregation expression for $project and $addFields. |
$text | $text aggregation expression for $project and $addFields. |
$where | $where aggregation expression for $project and $addFields. |
Pitfalls to avoid
Null poisons math
$add and $multiply return null if any operand is null. Wrap fields with $ifNull first.
String numbers
Arithmetic expects numeric BSON types. Use $toDouble or $convert on string amounts before math.
Operator vs accumulator
{ $sum: ["$a", "$b"] } in $project adds two fields on one doc. { $sum: "$amount" } in $group totals across docs.
Computed $match
Comparison operators in $match need a $expr wrapper—they are not the same as query shorthand like { score: { $gte: 80 } }.
❓ FAQ
Summary
- Scope: 136 operator tutorials covering math, strings, arrays, dates, logic, and type conversion.
- Pattern: operators are expressions inside stages—especially
$addFieldsand$project. - Next step: open MongoDB $abs Operator or start the learning path with
$add.
The same comparison operators ($eq, $gt, etc.) work in both aggregation expressions and query filters—but in $match with field comparisons you can often use the shorter query form without $expr. When comparing two fields on the same document, you need $expr. See the official aggregation quick reference.
9 people found this page helpful
