MongoDB $cond Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Conditional Logic

What You’ll Learn

The $cond operator adds if-then-else logic inside MongoDB aggregation pipelines. Use it to label records, compute derived fields, or return different values based on a condition.

01

If-Then-Else

Branch on true/false.

02

Syntax

if, then, else keys.

03

Comparisons

Pair with $gte, $eq.

04

$project Stage

Add computed fields.

05

Use Cases

Grades, status, defaults.

06

Nested $cond

Multi-tier decisions.

Definition and Usage

In MongoDB’s aggregation framework, the $cond operator evaluates a boolean condition and returns one of two expressions. Think of it as an inline if-then-else statement inside your pipeline. For example, assign "Pass" when a score is at least 70, otherwise "Fail".

💡
Beginner Tip

The if branch must evaluate to a boolean (true or false). Use comparison operators like $gte, $eq, or $and to build your condition.

📝 Syntax

$cond supports two equivalent forms. Beginners often find the object form easiest to read:

mongosh
{ $cond: { if: <condition>, then: <expression>, else: <expression> } }

Shorthand array form (same behavior):

mongosh
{ $cond: [ <condition>, <then-expression>, <else-expression> ] }

Syntax Rules

  • if — a boolean expression (often built with $gte, $lt, $eq, $and, etc.).
  • then — returned when the condition is true.
  • else — returned when the condition is false.
  • Both then and else can be strings, numbers, field references, or nested operators.
  • Use inside $project, $addFields, $set, or $group.
  • Nest $cond inside else (or then) for multi-way branching.

💡 $cond vs $ifNull

$cond — general if-then-else on any boolean condition
$ifNull — shortcut when you only need a default for null/missing values
Use $cond for comparisons; use $ifNull for simple null fallbacks

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (conditional)
Object syntax{ $cond: { if, then, else } }
Array syntax{ $cond: [ condition, then, else ] }
Condition typeMust evaluate to boolean
Common stages$project, $addFields, $set, $group
Pass / Fail
{
  $cond: {
    if: {
      $gte: [
        "$score",
        70
      ]
    },
    then: "Pass",
    else: "Fail"
  }
}

Grade by threshold

Array form
{
  $cond: [
    {
      $eq: [
        "$status",
        "active"
      ]
    },
    1,
    0
  ]
}

Shorthand syntax

Default value
{
  $cond: [
    {
      $gt: [
        "$qty",
        0
      ]
    },
    "$qty",
    0
  ]
}

Replace invalid qty

Nested
else: {
  $cond: [
    ...
  ]
}

Multi-tier logic

Examples Gallery

Label student grades, set inventory status, apply defaults, and build multi-tier letter grades with $cond.

📚 Basic Conditional Field

Use a students collection and assign Pass or Fail based on score.

Sample Input Documents

Suppose you have a students collection with name and score fields:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice",   "score": 85 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob",     "score": 70 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "score": 60 }
]

Example 1 — Pass or Fail by Score

Assign "Pass" when score >= 70, otherwise "Fail":

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      score: 1,
      grade: {
        $cond: {
          if: { $gte: ["$score", 70] },
          then: "Pass",
          else: "Fail"
        }
      }
    }
  }
])

How It Works

  • $project keeps name and adds a computed grade field.
  • $gte: ["$score", 70] returns true when score is 70 or higher.
  • Alice (85) and Bob (70) pass; Charlie (60) fails.

📈 Practical Patterns

Inventory labels, numeric defaults, and nested multi-tier grading.

Example 2 — Inventory Stock Status

Label products as "In Stock" or "Out of Stock" based on quantity:

mongosh
db.products.aggregate([
  {
    $addFields: {
      stockStatus: {
        $cond: [
          { $gt: ["$quantity", 0] },
          "In Stock",
          "Out of Stock"
        ]
      }
    }
  }
])

// quantity: 5  → "In Stock"
// quantity: 0  → "Out of Stock"

How It Works

This example uses the array shorthand form of $cond. $addFields adds the new field while keeping all existing fields in each document.

Example 3 — Numeric Default with $cond

Return the quantity when positive, otherwise use 0:

mongosh
db.orders.aggregate([
  {
    $project: {
      product: 1,
      safeQty: {
        $cond: {
          if: { $gt: ["$quantity", 0] },
          then: "$quantity",
          else: 0
        }
      }
    }
  }
])

How It Works

The then branch can reference a field ("$quantity") instead of a literal. This pattern sanitizes bad or negative values before reporting.

Example 4 — Nested $cond for Letter Grades

Chain conditions to assign A, B, C, or F:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      score: 1,
      letterGrade: {
        $cond: {
          if: { $gte: ["$score", 90] },
          then: "A",
          else: {
            $cond: {
              if: { $gte: ["$score", 80] },
              then: "B",
              else: {
                $cond: {
                  if: { $gte: ["$score", 70] },
                  then: "C",
                  else: "F"
                }
              }
            }
          }
        }
      }
    }
  }
])

// score 85 → "B"
// score 72 → "C"
// score 60 → "F"

How It Works

Each else branch contains another $cond, creating a decision tree. For many branches, consider $switch as a cleaner alternative.

🚀 Use Cases

  • Conditional aggregation — compute different values per document based on criteria.
  • Data transformation — categorize records, derive status labels, or map scores to grades.
  • Dynamic querying — return alternate field values inside reports without changing stored data.
  • Safe defaults — replace invalid or edge-case values with fallbacks during projection.

🧠 How $cond Works

1

MongoDB evaluates the if condition

Comparison or logical operators resolve to true or false for each document.

Condition
2

$cond picks a branch

True → then expression. False → else expression.

Branch
3

The result is stored in the pipeline

The chosen value becomes the new field value in $project or $addFields.

Output
=

Computed field per document

Each document gets its own result based on its data — no application code required.

Conclusion

The $cond operator brings if-then-else logic directly into MongoDB aggregation pipelines. It is ideal for labeling, grading, status fields, and conditional transformations without post-processing in your application.

Start with simple pass/fail conditions, then explore nested $cond or $switch for multi-way branching. Pair with comparison operators like $gte and $eq to build clear, readable conditions.

💡 Best Practices

✅ Do

  • Build conditions with $gte, $eq, $and, $or
  • Use the object form when learning; switch to array form when comfortable
  • Keep then and else the same type when possible
  • Use $switch when you have many branches
  • Test edge cases (exactly at threshold, null fields)

❌ Don’t

  • Put non-boolean values in the if branch
  • Nest too many $cond operators without considering $switch
  • Confuse $cond with $ifNull for general comparisons
  • Forget that $gte uses an array: ["$score", 70]
  • Assume pipeline order does not matter — conditions run per document in stage order

Key Takeaways

Knowledge Unlocked

Five things to remember about $cond

Use these points when adding conditional logic in MongoDB.

5
Core concepts
📝 02

if / then / else

Object or array form.

Syntax
📏 03

Boolean if

Use $gte, $eq, etc.

Rule
🛠 04

Any Expression

then/else can nest ops.

Flexibility
05

Not $ifNull

General conditions.

Important

❓ Frequently Asked Questions

$cond evaluates a boolean condition and returns one of two expressions — the then value when true, or the else value when false. It is MongoDB's if-then-else for aggregation pipelines.
Object form: { $cond: { if: <condition>, then: <expression>, else: <expression> } }. Shorthand array form: { $cond: [ <condition>, <then>, <else> ] }.
Yes. Both branches can be literals, field references, or nested operators like $multiply, $concat, or another $cond.
$cond checks any boolean condition. $ifNull only tests whether a value is null or missing and returns a default if so.
Inside $project, $addFields, $set, $group accumulators, and other stages that accept aggregation expressions.

Continue the Operator Series

Move on to $convert for type conversion, or review $concatArrays for merging arrays.

Next: $convert →

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.

5 people found this page helpful