MongoDB $cond Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $cond?

$cond is MongoDB’s if-then-else for aggregation. It tests a boolean condition and returns one of two values: the then branch when true, or the else branch when false.

Remember
$cond = if / then / else for aggregation

Object form (clearer):
{ $cond: { if: <bool>, then: <A>, else: <B> } }

Array form (shorter):
{ $cond: [ <bool>, <A>, <B> ] }

true  → return A (then)
false → return B (else)
all three parts required
UsePrefer
One if / else choice$cond
Many cases$switch
Null / missing default only$ifNull

How to Use $cond in MongoDB

Write a boolean test, then pick the value for true and the value for false.

  1. Choose an expression stage ($addFields or $project).
  2. Build a boolean condition (often with $gte, $eq, or $and).
  3. Pass if, then, and else (object form) or [if, then, else] (array form).
  4. Use the returned value as a new field, label, price, or nested expression.
PieceRequired?Role
ifYesBoolean expression to test
thenYesValue when the condition is true
elseYesValue when the condition is false

Pseudocode

Pseudocode
for each document:
    condition = evaluate(ifExpression)
    if condition is true:
        result = evaluate(thenExpression)
    else:
        result = evaluate(elseExpression)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing conditional expressions.

TopicDetail
TypeAggregation expression (not a find filter alone)
Object syntax{ $cond: { if, then, else } }
Array syntax{ $cond: [ if, then, else ] }
Discount patternqty >= 250 ? 30 : 20
Label patternscore >= 50 ? "Pass" : "Fail"
vs $switchOne branch vs many cases
vs $ifNullAny boolean vs null/missing only

Live Preview

Rule: if qty >= 250 then discount 30, else 20. Change quantity and watch $cond pick a branch.

Simulates $cond with $gte: ["$qty", 250] (same idea as the mongosh examples).

Result
qty = 250
$gte(qty, 250) → true
$cond → then → 30

{ discount: 30 }

Worked Walkthrough — Bulk Discount

Rule: if quantity is at least 250, discount is 30; otherwise discount is 20.

Calculation
Rule:
  if qty >= 250 then 30 else 20

qty = 300
  300 >= 250 → true
  $cond → then → 30

qty = 250
  250 >= 250 → true
  $cond → then → 30

qty = 200
  200 >= 250 → false
  $cond → else → 20

Think: one question, two possible answers.

MongoDB Examples

We use a small inventory collection. First we set a discount with the object form of $cond, then we repeat with the shorter array form. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine four inventory items. Each document has an item code and a quantity. We save them in a collection named inventory.

mongosh
db.inventory.insertMany([
  { _id: 1, item: "abc1", qty: 300 },
  { _id: 2, item: "abc2", qty: 200 },
  { _id: 3, item: "xyz1", qty: 250 },
  { _id: 4, item: "VWZ2", qty: 180 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps four documents in inventory. Run find() to see them:

mongosh
db.inventory.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1 … 4Document id for this lesson
item"abc1"Product / SKU code
qty300Quantity on hand
Picture
Discount rule:

  qty >= 250  →  discount 30  (bulk)
  qty <  250  →  discount 20  (normal)

  300, 250 → then → 30
  200, 180 → else → 20

How It Works

  1. Insert once. insertMany adds four inventory documents.
  2. MongoDB stores fields as written. Each row keeps item and qty as plain values.
  3. find() shows the same shape. What you inserted is what you get back—ready for $cond next.

Example 2 — Object Form (if / then / else)

Goal: add a discount field. If qty >= 250, use 30; otherwise use 20. Object form is easiest to read.

mongosh
db.inventory.aggregate([
  {
    $addFields: {
      discount: {
        $cond: {
          if: { $gte: ["$qty", 250] },
          then: 30,
          else: 20
        }
      }
    }
  }
]);

How It Works

  1. Test qty. $gte: ["$qty", 250] asks “is quantity at least 250?”
  2. True branch. For 300 and 250, then: 30 is returned.
  3. False branch. For 200 and 180, else: 20 is returned.
  4. Keep all rows. $addFields adds discount; nothing is filtered out.

Example 3 — Array Form (Shorthand)

Same rule, shorter syntax: [ condition, then, else ]. Results match Example 2.

mongosh
db.inventory.aggregate([
  {
    $addFields: {
      discount: {
        $cond: [
          { $gte: ["$qty", 250] },
          30,
          20
        ]
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the four inventory rows from Example 1.
  2. Same three parts. Position 0 = if, 1 = then, 2 = else.
  3. Same answers. 300/250 → 30; 200/180 → 20.
  4. Pick a style. Object form is clearer for beginners; array form is shorter once you know the order.

Edge Cases & Pitfalls

Check these before shipping $cond logic.

required

All three parts are required

You must supply if, then, and else. There is no optional else branch.

boolean

Condition should be boolean

Use comparison operators ($gte, $eq, …) or logical ops. A bare number is not a clear boolean test.

many

Many branches? Prefer $switch

Nested $cond chains get hard to read. Use $switch for several cases.

null

Null defaults are $ifNull

If you only care about missing or null values, $ifNull is simpler than a full $cond.

Performance Notes

ApproachCostBest for
$cond alonePer-document branchLabels, discounts, flags
Nested $condHarder to readTwo or three levels max
$switchSimilar cost, clearerMany discrete cases

Conditional expressions are cheap compared with sorts or joins. Filter early with $match when only some documents need a computed value.

Key Takeaways

  • Role: if-then-else for aggregation expressions.
  • Syntax: object form or [if, then, else] array form.
  • Required: always provide if, then, and else.
  • Many cases: prefer $switch; null defaults: $ifNull.

One line: $cond answers “if this is true, return A; otherwise return B.”

Frequently Asked Questions

$cond is if-then-else for aggregation. It evaluates a boolean condition and returns the then value when true, or the else value when false.
Object form: { $cond: { if: <condition>, then: <trueCase>, else: <falseCase> } }. Array form: { $cond: [ <condition>, <trueCase>, <falseCase> ] }. Both require all three parts.
Yes. They can be literals, field paths, or nested operators such as $multiply, $concat, or another $cond.
$cond checks any boolean condition. $ifNull only replaces null or missing values with a default.
$cond handles one if/else branch. $switch is better when you have many cases (like a switch statement).
Inside aggregation expression stages such as $project, $addFields, and other places that accept expressions—not as a standalone find() filter.

Next: $convert

Convert values between BSON types with optional onError / onNull.

$convert tutorial →

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