Bird
Raised Fist0
MongoDBquery~10 mins

Combining logical and comparison operators in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Combining logical and comparison operators
Start with collection
Apply comparison operators
Combine with logical operators
Filter documents matching all conditions
Return filtered documents
We first check individual conditions using comparison operators, then combine these conditions using logical operators to filter documents.
Execution Sample
MongoDB
db.products.find({
  $and: [
    { price: { $gt: 20 } },
    { category: { $eq: "books" } }
  ]
})
This query finds products with price greater than 20 and category equal to 'books'.
Execution Table
StepDocumentCheck price > 20Check category == 'books'Logical $and ResultInclude in Result
1{"name":"Book A", "price":25, "category":"books"}TrueTrueTrueYes
2{"name":"Book B", "price":15, "category":"books"}FalseTrueFalseNo
3{"name":"Pen", "price":30, "category":"stationery"}TrueFalseFalseNo
4{"name":"Book C", "price":22, "category":"books"}TrueTrueTrueYes
5{"name":"Notebook", "price":18, "category":"books"}FalseTrueFalseNo
6End of collection----
💡 All documents checked; only those matching both conditions included.
Variable Tracker
VariableStartAfter Doc 1After Doc 2After Doc 3After Doc 4After Doc 5Final
price > 20N/ATrueFalseTrueTrueFalseN/A
category == 'books'N/ATrueTrueFalseTrueTrueN/A
$and resultN/ATrueFalseFalseTrueFalseN/A
Key Moments - 2 Insights
Why does a document with price 15 and category 'books' get excluded?
Because the price > 20 condition is False for that document (see execution_table row 2), and $and requires all conditions to be True.
What happens if one condition in $and is False?
The whole $and condition becomes False, so the document is excluded (see rows 2, 3, and 5 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the $and result for the document {"name":"Pen", "price":30, "category":"stationery"}?
AUndefined
BTrue
CFalse
DNull
💡 Hint
Check row 3 under 'Logical $and Result' in the execution_table.
At which step does the document get included in the result set?
AStep 2
BStep 1
CStep 3
DStep 5
💡 Hint
Look for 'Include in Result' column with 'Yes' in execution_table.
If the logical operator was changed from $and to $or, which document would be included at step 5?
AIncluded
BExcluded
CDepends on price only
DDepends on category only
💡 Hint
With $or, only one condition needs to be True; check price and category values in variable_tracker.
Concept Snapshot
MongoDB queries combine comparison operators like $gt, $eq to check conditions.
Logical operators like $and combine these conditions.
All conditions in $and must be true for a document to match.
Use $or to match if any condition is true.
This filters documents from collections based on multiple criteria.
Full Transcript
This visual execution shows how MongoDB combines logical and comparison operators to filter documents. Each document is checked against comparison conditions like price greater than 20 and category equals 'books'. These conditions are combined with the $and logical operator, which requires all conditions to be true for the document to be included in the result. The execution table traces each document's evaluation step by step, showing which documents pass or fail the combined conditions. The variable tracker shows how each condition's result changes per document. Key moments clarify why some documents are excluded. The quiz tests understanding of the logical flow and results. This helps beginners see how MongoDB queries work internally when combining conditions.

Practice

(1/5)
1. Which MongoDB operator is used to combine multiple conditions where all must be true?
easy
A. $gt
B. $and
C. $or
D. $lt

Solution

  1. Step 1: Understand logical operators

    $and requires all conditions inside it to be true for a document to match.
  2. Step 2: Compare with other operators

    $or requires any condition to be true, $gt and $lt are comparison operators, not logical combiners.
  3. Final Answer:

    $and -> Option B
  4. Quick Check:

    All conditions true = $and [OK]
Hint: Use $and to require all conditions true [OK]
Common Mistakes:
  • Confusing $and with $or
  • Using comparison operators as logical
  • Mixing $gt with $and
2. Which of the following is the correct syntax using $and to find documents where age is greater than 25 and status is 'active'?
easy
A. { $and: [ { age: { $gt: 25 } }, { status: 'active' } ] }
B. { $or: [ { age: { $gt: 25 } }, { status: 'active' } ] }
C. { age: { $gt: 25 }, status: 'active' }
D. { $and: { age: { $gt: 25 }, status: 'active' } }

Solution

  1. Step 1: Check $and syntax

    $and requires an array of conditions, so the value must be an array of objects.
  2. Step 2: Validate other options

    { $or: [ { age: { $gt: 25 } }, { status: 'active' } ] } uses $or, { age: { $gt: 25 }, status: 'active' } uses implicit AND but not with $and operator, { $and: { age: { $gt: 25 }, status: 'active' } } uses $and with an object instead of array which is invalid.
  3. Final Answer:

    { $and: [ { age: { $gt: 25 } }, { status: 'active' } ] } -> Option A
  4. Quick Check:

    $and needs array of conditions [OK]
Hint: Use array inside $and for multiple conditions [OK]
Common Mistakes:
  • Using object instead of array in $and
  • Confusing $and with $or
  • Missing $gt operator syntax
3. Given the collection documents: [{ age: 30, status: 'active' }, { age: 20, status: 'inactive' }, { age: 40, status: 'active' }], what documents match this query?
{ $or: [ { age: { $lt: 25 } }, { status: 'active' } ] }
medium
A. [{ age: 30, status: 'active' }, { age: 40, status: 'active' }]
B. []
C. [{ age: 20, status: 'inactive' }]
D. [{ age: 20, status: 'inactive' }, { age: 30, status: 'active' }, { age: 40, status: 'active' }]

Solution

  1. Step 1: Understand $or condition

    Documents match if age is less than 25 OR status is 'active'.
  2. Step 2: Check each document

    First doc: age 30 (not <25), status 'active' (matches). Second doc: age 20 (<25), status 'inactive' (matches age condition). Third doc: age 40 (not <25), status 'active' (matches).
  3. Final Answer:

    All three documents match -> Option D
  4. Quick Check:

    $or matches any condition true [OK]
Hint: Any condition true in $or returns document [OK]
Common Mistakes:
  • Ignoring one condition in $or
  • Confusing $or with $and
  • Wrongly excluding documents
4. Identify the error in this MongoDB query to find documents where score is greater than 50 and less than 100:
{ $and: { score: { $gt: 50 }, score: { $lt: 100 } } }
medium
A. Using object instead of array inside $and
B. Using $gt and $lt together is invalid
C. Missing $or operator
D. score field should be inside $or

Solution

  1. Step 1: Check $and operator usage

    $and requires an array of condition objects, not a single object with repeated keys.
  2. Step 2: Understand object key overwrite

    In the object, 'score' key appears twice, so only the last one is used, causing incorrect query.
  3. Final Answer:

    Using object instead of array inside $and -> Option A
  4. Quick Check:

    $and needs array, not object with duplicate keys [OK]
Hint: Use array for $and conditions to avoid key overwrite [OK]
Common Mistakes:
  • Using object with duplicate keys in $and
  • Confusing $and with $or
  • Thinking $gt and $lt can't combine
5. You want to find documents where (age is greater than 30 and status is 'active') or (score is less than 50). Which query correctly combines these conditions?
hard
A. { $and: { $or: [ { age: { $gt: 30 } }, { status: 'active' } ], score: { $lt: 50 } } }
B. { $and: [ { age: { $gt: 30 } }, { status: 'active' }, { score: { $lt: 50 } } ] }
C. { $or: [ { $and: [ { age: { $gt: 30 } }, { status: 'active' } ] }, { score: { $lt: 50 } } ] }
D. { $or: { age: { $gt: 30 }, status: 'active', score: { $lt: 50 } } }

Solution

  1. Step 1: Break down the condition

    We want documents matching either (age > 30 AND status = 'active') OR (score < 50).
  2. Step 2: Match query structure

    { $or: [ { $and: [ { age: { $gt: 30 } }, { status: 'active' } ] }, { score: { $lt: 50 } } ] } uses $or with two parts: one $and array for age and status, and one condition for score less than 50, matching the requirement exactly.
  3. Final Answer:

    { $or: [ { $and: [ { age: { $gt: 30 } }, { status: 'active' } ] }, { score: { $lt: 50 } } ] } -> Option C
  4. Quick Check:

    Nested $and inside $or matches complex logic [OK]
Hint: Use nested $and inside $or for combined conditions [OK]
Common Mistakes:
  • Using $and instead of $or for main condition
  • Wrong object instead of array syntax
  • Mixing $or and $and incorrectly