MongoDB Aggregation Operators

Beginner
⏱️ 18 min read
📚 Updated: Jul 2026
🎯 136 Tutorials
Aggregation

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 $add through $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 $project and $addFields.
  • Expression syntax: { $add: [ "$a", "$b" ] } — operator name as key, arguments in an array or object.
  • Null handling: many operators return null when 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.

GoalStart withNotes
Line total or sum fields$add / $multiplyChain in one expression or use multiple computed fields.
Handle missing values$ifNullReplace null before math or concatenation.
Conditional column$cond or $switchTernary vs multi-branch logic.
Compare field values$eq, $gteUse inside $expr for computed filters.
Format dates in reports$dateToStringControl format with format and timezone.
Filter array elements$filterKeep items matching a sub-expression.
Totals per group$sum accumulatorNot an operator—runs inside $group.
1

Multiple operators in one $addFields

Compute subtotal, apply a discount flag, and format the order date—four operators, one stage.

mongosh
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.

  1. Math: $add, $subtract, $multiply, $divide.
  2. Nulls & logic: $ifNull, $cond, $and, $or.
  3. Compare: $eq, $gte with $expr in $match.
  4. Strings: $concat, $toUpper, $trim.
  5. Arrays: $filter, $map, $size.
  6. Dates: $dateToString, $dateAdd, $dateDiff.
  7. Then accumulators: $sum and $avg inside $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

OperatorWhat it does
$addAdd numbers or milliseconds to a date.
$subtractSubtract numbers or compute date differences.
$multiplyMultiply numeric expressions together.
$divideDivide one number by another.
$modReturn the remainder after division.
$absAbsolute value of a number.
$ceilRound a number up to the nearest integer.
$floorRound a number down to the nearest integer.
$roundRound to nearest integer with optional decimal places.
$truncTruncate toward zero (drop fractional part).
$sqrtSquare root of a non-negative number.
$powRaise a number to an exponent.
$expEuler's number e raised to a power.
$lnNatural logarithm (base e).
$logLogarithm of a number in a given base.
$log10Base-10 logarithm.
$randRandom float from 0 to 1 (non-deterministic).

Trigonometry

OperatorWhat 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

OperatorWhat it does
$cmpThree-way compare: returns -1, 0, or 1.
$eqTrue when two values are equal.
$neTrue when two values are not equal.
$gtTrue when first value is greater.
$gteTrue when first value is greater or equal.
$ltTrue when first value is less.
$lteTrue when first value is less or equal.

Logical & conditional

OperatorWhat it does
$andTrue when every argument is true.
$orTrue when any argument is true.
$notLogical negation of a boolean expression.
$norTrue when no argument is true.
$condIf-then-else conditional expression.
$switchMulti-branch conditional (like switch/case).
$ifNullReplace null or missing with a fallback value.

Arrays

OperatorWhat it does
$arrayElemAtReturn the element at a zero-based array index.
$concatArraysConcatenate multiple arrays into one.
$filterKeep 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.
$mapApply an expression to each array element.
$range$range aggregation expression for $project and $addFields.
$reduceFold an array into a single accumulated value.
$reverseArray$reverseArray aggregation expression for $project and $addFields.
$sizeCount elements in an array.
$sliceReturn 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.
$inTrue when a value exists in an array.

Sets

OperatorWhat 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

OperatorWhat it does
$concatJoin 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.
$toLowerConvert string to lowercase.
$toUpperConvert string to uppercase.
$trimRemove leading and trailing whitespace.
$ltrim$ltrim aggregation expression for $project and $addFields.
$rtrim$rtrim aggregation expression for $project and $addFields.
$splitSplit 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

OperatorWhat it does
$dateAddAdd units (day, month, etc.) to a date.
$dateDiffDifference 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.
$dateToStringFormat 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

OperatorWhat it does
$convertConvert a value to a specified BSON type.
$toBoolConvert input to Bool type.
$toDateConvert input to Date type.
$toDecimalConvert input to Decimal type.
$toDoubleConvert input to Double type.
$toIntConvert input to Int type.
$toLongConvert input to Long type.
$toObjectIdConvert input to ObjectId type.
$toStringConvert input to String type.
$typeReturn the BSON type of a value as a number.
$isNumber$isNumber aggregation expression for $project and $addFields.

Document, query & misc

OperatorWhat 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.
$existsMatch documents where a field exists or is missing.
$exprUse 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.
$letDefine variables for use in sub-expressions.
$literalReturn 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

Null poisons math

$add and $multiply return null if any operand is null. Wrap fields with $ifNull first.

types

String numbers

Arithmetic expects numeric BSON types. Use $toDouble or $convert on string amounts before math.

$sum

Operator vs accumulator

{ $sum: ["$a", "$b"] } in $project adds two fields on one doc. { $sum: "$amount" } in $group totals across docs.

$expr

Computed $match

Comparison operators in $match need a $expr wrapper—they are not the same as query shorthand like { score: { $gte: 80 } }.

❓ FAQ

An aggregation operator is an expression used inside pipeline stages like $project, $addFields, $match ($expr), and $group (non-accumulator fields). Examples include $add for math, $concat for strings, and $cond for conditionals.
Most run per document inside $project or $addFields: { total: { $add: ["$price", "$tax"] } }. Comparison operators like $eq also work inside $match when wrapped in $expr.
Operators compute values for each document individually. Accumulators ($sum, $avg, $push, etc.) roll up many documents inside $group. Some names like $sum exist in both forms with different syntax.
Start with $add, $subtract, $multiply, $cond, $eq, $ifNull, $concat, and $dateToString. That set covers pricing logic, null handling, labels, and formatted dates in reports.
Query operators like $gt and $in appear in find() filters. The same comparison operators can appear in aggregation via $expr. Aggregation also adds math, string, array, and date expression operators not used in plain find().
URLs use collapsed lowercase slugs without dollar signs: /mongodb/operators/add for $add, /mongodb/operators/dateadd for $dateAdd. Multi-word operator names use camelCase collapsed into one slug.

Summary

  • Scope: 136 operator tutorials covering math, strings, arrays, dates, logic, and type conversion.
  • Pattern: operators are expressions inside stages—especially $addFields and $project.
  • Next step: open MongoDB $abs Operator or start the learning path with $add.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful