MongoDB Expressions

Intermediate
9 min read
Updated: Nov 2026
Getting Started

What Is Expressions?

An aggregation expression computes a value inside a pipeline stage. Expressions can be a field path like "$price", a literal, a variable like "$$NOW", or an operator expression such as { $multiply: ["$price", "$qty"] }. Operator expressions take other expressions as arguments, so they nest into trees. Stages like $project, $addFields, and $group accept expressions to build new fields.

Why It Matters

ReasonBenefit
Compute inside the databaseDerived fields such as totals and labels are calculated without extra application code.
ComposableSmall operators combine into larger formulas by nesting.
Used everywhere in pipelinesUnderstanding expressions unlocks $project, $addFields, $group, and more.
Bridge to the operator referenceEach operator in the reference is simply an expression you plug in.

How To Use It

  1. Create an orders collection with price, qty, and discount fields.
  2. Start an aggregate() pipeline with a $project stage.
  3. Reference an existing field using a field path such as "$price".
  4. Create a computed field with { $multiply: ["$price", "$qty"] }.
  5. Nest another operator, for example $subtract with the discount, to build a tree.
  6. Use $cond to produce a label based on a computed total.
  7. Reuse the same expression idea inside $group to compute per-group values.

mongosh Examples

mongosh
db.orders.insertMany([
  { item: "pen", price: 10, qty: 5, discount: 2 },
  { item: "book", price: 200, qty: 2, discount: 20 },
  { item: "bag", price: 800, qty: 1, discount: 0 }
])

db.orders.aggregate([
  {
    $project: {
      _id: 0,
      item: 1,
      // nested expression tree: (price * qty) - discount
      net: { $subtract: [{ $multiply: ["$price", "$qty"] }, "$discount"] },
      size: {
        $cond: [{ $gte: [{ $multiply: ["$price", "$qty"] }, 400] }, "large", "small"]
      },
      label: { $concat: ["$item", " x", { $toString: "$qty" }] }
    }
  }
])

// Same expressions inside $group
db.orders.aggregate([
  { $group: { _id: null, revenue: { $sum: { $multiply: ["$price", "$qty"] } } } }
])

Edge Cases & Pitfalls

Field path vs string literal

In a $project expression "$name" reads the field. To output the text $name, wrap it in $literal.

Query operators are different

Inside $match you can use filter-style operators like $gt, but to use them in $project you need the aggregation versions, such as { $gt: ["$a", 5] }.

Null and missing values

Arithmetic on null or a missing field usually returns null. Guard with $ifNull when fields may be absent.

Type mismatches

$add on a string and number fails or behaves unexpectedly. Convert first with $toInt, $toDouble, or $toString.

Cheat Sheet

TopicDetail
"$field"Field path: value of the field in the current document
"$a.b"Field path into an embedded document
"$$NOW"System variable holding the current date and time
"$$ROOT"The whole current document
{ $add: [a, b] }Operator expression with an array of arguments
{ $multiply: [a, b] }Arithmetic expression; $subtract, $divide also exist
{ $concat: [a, " ", b] }String expression for joining text
{ $cond: [test, then, else] }Conditional expression (if/else)
{ $literal: "$x" }Return a value without interpreting the $
NestingAny argument can itself be another expression

Key Takeaways

A leading $ on a string inside an aggregation expression means a field path. These are aggregation expression operators, different from the query operators used in $match filters.

Frequently Asked Questions

What is an aggregation expression?

A piece of syntax that evaluates to a value in a pipeline stage: a field path, literal, variable, or operator expression.

What does the dollar sign mean in "$price"?

In aggregation expressions, a string starting with $ is a field path that reads that field from the current document.

What is $$ROOT?

A system variable that refers to the entire current document in the pipeline.

Can I nest expressions?

Yes. Most operator arguments can be other expressions, forming an expression tree.

How do expressions differ from query operators?

Query operators such as $gt in a filter match documents. Expression operators compute values and take their operands in an array, for example { $gt: ["$a", 5] }.

Where can I find all expression operators?

See the MongoDB operators hub on CodeToFun, which groups operators by category.

Next: MongoDB Connection String

Continue the MongoDB learning path.

MongoDB Connection String →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

8 people found this page helpful