Nearby lessons

20 of 22

🧩 MongoDB: Conditional Operators

MongoDB conditional operators allow you to apply logic similar to if-else statements within the aggregation pipeline. These operators let you handle conditional calculations, replace null values, or perform multi-case branching.

📚 Sample Data Setup — employees Collection

MongoDB Shell
NoSQL
Database
1db.employees.insertMany([
2 { _id: 1, name: "Alice", salary: 50000, bonus: 2000, department: "Engineering" },
3 { _id: 2, name: "Bob", salary: 45000, bonus: null, department: "Marketing" },
4 { _id: 3, name: "Cara", salary: 60000, bonus: 5000, department: null }
5]);
Query Result
JSON Output
✅ 3 employee documents inserted successfully.

1️⃣ Using $cond — Ternary If-Then-Else

MongoDB Shell
NoSQL
Database
1db.employees.aggregate([
2 {
3 $project: {
4 name: 1,
5 adjustedBonus: {
6 $cond: {
7 if: { $gt: ["$salary", 50000] },
8 then: { $multiply: ["$bonus", 1.5] },
9 else: "$bonus"
10 }
11 }
12 }
13 }
14]);
Query Result
JSON Output
[
{ "_id": 1, "name": "Alice", "adjustedBonus": 2000 },
{ "_id": 2, "name": "Bob", "adjustedBonus": null },
{ "_id": 3, "name": "Cara", "adjustedBonus": 7500 }
]

2️⃣ Using $ifNull — Replace Null Values

MongoDB Shell
NoSQL
Database
1db.employees.aggregate([
2 {
3 $project: {
4 name: 1,
5 safeBonus: { $ifNull: ["$bonus", 0] },
6 safeDepartment: { $ifNull: ["$department", "Unassigned"] }
7 }
8 }
9]);
Query Result
JSON Output
[
{ "_id": 1, "name": "Alice", "safeBonus": 2000, "safeDepartment": "Engineering" },
{ "_id": 2, "name": "Bob", "safeBonus": 0, "safeDepartment": "Marketing" },
{ "_id": 3, "name": "Cara", "safeBonus": 5000, "safeDepartment": "Unassigned" }
]

3️⃣ Using $switch — Multi-Case Conditional

MongoDB Shell
NoSQL
Database
1db.employees.aggregate([
2 {
3 $project: {
4 name: 1,
5 salaryTier: {
6 $switch: {
7 branches: [
8 { case: { $lt: ["$salary", 45000] }, then: "Entry" },
9 { case: { $lt: ["$salary", 55000] }, then: "Mid" },
10 { case: { $gte: ["$salary", 55000] }, then: "Senior" }
11 ],
12 default: "Unknown"
13 }
14 }
15 }
16 }
17]);
Query Result
JSON Output
[
{ "_id": 1, "name": "Alice", "salaryTier": "Mid" },
{ "_id": 2, "name": "Bob", "salaryTier": "Mid" },
{ "_id": 3, "name": "Cara", "salaryTier": "Senior" }
]
Keep Going!MongoDB - Import JSON