Bird
Raised Fist0
MongoDBquery~20 mins

$elemMatch for complex array queries in MongoDB - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
MongoDB $elemMatch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Find documents with a matching array element using $elemMatch
Given a collection products where each document has an array field reviews with objects containing rating and comment, which query returns products that have at least one review with a rating greater than 4 and a comment containing the word 'excellent'?
MongoDB
db.products.find({ reviews: { $elemMatch: { rating: { $gt: 4 }, comment: /excellent/i } } })
Adb.products.find({ reviews: { $elemMatch: { rating: { $gte: 4 }, comment: /excellent/ } } })
Bdb.products.find({ reviews: { rating: { $gt: 4 }, comment: /excellent/i } })
Cdb.products.find({ reviews: { $elemMatch: { rating: 4, comment: 'excellent' } } })
Ddb.products.find({ reviews: { $elemMatch: { rating: { $gt: 4 }, comment: /excellent/i } } })
Attempts:
2 left
💡 Hint
Use $elemMatch to match multiple conditions on the same array element.
🧠 Conceptual
intermediate
1:30remaining
Understanding $elemMatch behavior with multiple conditions
What does the $elemMatch operator do when used in a query on an array field?
AIt matches documents where at least one array element satisfies all specified conditions inside $elemMatch.
BIt matches documents where all array elements satisfy each condition separately.
CIt matches documents where any array element satisfies at least one of the conditions inside $elemMatch.
DIt matches documents where the array contains exactly one element.
Attempts:
2 left
💡 Hint
Think about how $elemMatch applies conditions to a single element.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in $elemMatch usage
Which of the following queries will cause a syntax error when using $elemMatch in MongoDB?
Adb.collection.find({ items: { $elemMatch: { price: { $lt: 20 }, qty: { $gt: 5 } } } })
Bdb.collection.find({ items: { $elemMatch: { qty: { $gt: 5 } } } })
Cdb.collection.find({ items: { $elemMatch: price: { $lt: 20 }, qty: { $gt: 5 } } })
Ddb.collection.find({ items: { $elemMatch: { price: { $lt: 20 } } } })
Attempts:
2 left
💡 Hint
Check the brackets and object syntax inside $elemMatch.
optimization
advanced
2:00remaining
Optimizing queries with $elemMatch on large arrays
When querying documents with large arrays, which approach using $elemMatch is generally more efficient?
AUse $elemMatch to combine multiple conditions on the same array element instead of separate queries for each condition.
BUse multiple $elemMatch operators on the same array field for each condition separately.
CAvoid $elemMatch and use $or with separate conditions on the array field.
DUse $elemMatch only with a single condition to reduce complexity.
Attempts:
2 left
💡 Hint
Think about how MongoDB can use indexes and reduce scanning.
🔧 Debug
expert
2:30remaining
Why does this $elemMatch query return no results?
Consider the collection orders with documents containing an array items. Each item has productId and quantity. The query below returns no documents, but you expect some matches:

db.orders.find({ items: { $elemMatch: { productId: 123, quantity: { $gt: 10 } } } })

What is the most likely reason?
AThe quantity field is missing in all array elements.
BNo single array element has both productId 123 and quantity greater than 10; conditions are split across elements.
CThe $elemMatch operator cannot be used with numeric comparisons.
DThe productId field is stored as a string, but the query uses a number.
Attempts:
2 left
💡 Hint
Remember $elemMatch matches conditions on the same element, not across elements.

Practice

(1/5)
1. What does the $elemMatch operator do in MongoDB queries?
easy
A. Matches documents where any array element matches any one condition.
B. Updates all elements in an array regardless of conditions.
C. Finds array elements that match all specified conditions together.
D. Deletes array elements that do not match the condition.

Solution

  1. Step 1: Understand array queries

    MongoDB arrays can contain multiple elements, and queries may need to check multiple conditions on the same element.
  2. Step 2: Role of $elemMatch

    $elemMatch ensures all conditions apply to the same array element, not spread across different elements.
  3. Final Answer:

    Finds array elements that match all specified conditions together. -> Option C
  4. Quick Check:

    $elemMatch = all conditions on one element [OK]
Hint: Use $elemMatch to match multiple conditions on one array item [OK]
Common Mistakes:
  • Thinking $elemMatch matches conditions across different elements
  • Confusing $elemMatch with $in or $all
  • Assuming $elemMatch updates or deletes elements
2. Which of the following is the correct syntax to find documents where an array field scores has an element with score greater than 80 and type equal to 'exam' using $elemMatch?
easy
A. { scores: { $elemMatch: { $gt: 80, type: 'exam' } } }
B. { scores: { $elemMatch: { score: { $gt: 80 } }, type: 'exam' } }
C. { scores: { $elemMatch: { score: { $gt: 80 } }, type: { $eq: 'exam' } } }
D. { scores: { $elemMatch: { score: { $gt: 80 }, type: 'exam' } } }

Solution

  1. Step 1: Understand $elemMatch syntax

    The correct syntax requires an object inside $elemMatch with each condition as a field: score with $gt operator and type with exact match.
  2. Step 2: Analyze options

    { scores: { $elemMatch: { $gt: 80, type: 'exam' } } } misuses $gt without a field name. { scores: { $elemMatch: { score: { $gt: 80 } }, type: 'exam' } } incorrectly places type outside $elemMatch. { scores: { $elemMatch: { score: { $gt: 80 } }, type: { $eq: 'exam' } } } also incorrectly places type outside $elemMatch. { scores: { $elemMatch: { score: { $gt: 80 }, type: 'exam' } } } correctly places both conditions inside $elemMatch.
  3. Final Answer:

    { scores: { $elemMatch: { score: { $gt: 80 }, type: 'exam' } } } -> Option D
  4. Quick Check:

    Both conditions inside $elemMatch object [OK]
Hint: Put all conditions inside one $elemMatch object [OK]
Common Mistakes:
  • Placing some conditions outside $elemMatch
  • Using $gt without field name
  • Misplacing the type condition outside $elemMatch
3. Given the collection documents:
{ _id: 1, grades: [ { score: 85, type: 'exam' }, { score: 70, type: 'quiz' } ] }
{ _id: 2, grades: [ { score: 90, type: 'quiz' }, { score: 75, type: 'exam' } ] }

What documents will this query return?
{ grades: { $elemMatch: { score: { $gt: 80 }, type: 'exam' } } }
medium
A. Only document with _id: 1
B. Only document with _id: 2
C. Both documents with _id: 1 and _id: 2
D. No documents

Solution

  1. Step 1: Check document _id: 1

    It has grades with score 85 and type 'exam' which matches score > 80 and type 'exam'. So it matches.
  2. Step 2: Check document _id: 2

    Grades are {score: 90, type: 'quiz'} and {score: 75, type: 'exam'}. No single element has both score > 80 and type 'exam' together.
  3. Final Answer:

    Only document with _id: 1 -> Option A
  4. Quick Check:

    Match requires both conditions on same element [OK]
Hint: Check each array element for all conditions together [OK]
Common Mistakes:
  • Matching documents if conditions appear in different elements
  • Ignoring the type field condition
  • Assuming any element with score > 80 matches
4. You wrote this query to find documents where items array has an element with price less than 20 and qty greater than 5:
{ items: { $elemMatch: { price: { $lt: 20 }, qty: { $gt: 5 } } } }

But it returns no results, even though you know such documents exist. What is the likely problem?
medium
A. You should use $and instead of $elemMatch.
B. The fields price and qty are not in the same array element.
C. The query syntax is invalid and causes an error.
D. MongoDB does not support comparison operators inside $elemMatch.

Solution

  1. Step 1: Understand $elemMatch behavior

    $elemMatch requires all conditions to be true on the same array element.
  2. Step 2: Analyze the problem

    If price < 20 and qty > 5 exist but in different elements, the query returns no results because no single element satisfies both.
  3. Final Answer:

    The fields price and qty are not in the same array element. -> Option B
  4. Quick Check:

    All conditions must match one element [OK]
Hint: Check if conditions apply to same array element [OK]
Common Mistakes:
  • Assuming $elemMatch matches conditions across elements
  • Thinking $and replaces $elemMatch for arrays
  • Believing MongoDB disallows operators inside $elemMatch
5. You have a collection of products with a field reviews which is an array of objects like { rating: Number, user: String, verified: Boolean }. You want to find products that have at least one review with rating >= 4, user 'Alice', and verified true. Which query correctly uses $elemMatch to achieve this?
hard
A. { reviews: { $elemMatch: { rating: { $gte: 4 }, user: 'Alice', verified: true } } }
B. { reviews: { rating: { $gte: 4 }, user: 'Alice', verified: true } }
C. { reviews: { $all: [ { rating: { $gte: 4 } }, { user: 'Alice' }, { verified: true } ] } }
D. { reviews: { $elemMatch: { rating: 4, user: 'Alice', verified: true } } }

Solution

  1. Step 1: Understand the conditions

    We want one review element where rating is at least 4, user is 'Alice', and verified is true.
  2. Step 2: Analyze query options

    { reviews: { $elemMatch: { rating: { $gte: 4 }, user: 'Alice', verified: true } } } correctly uses $elemMatch with all conditions combined, including $gte for rating. { reviews: { rating: { $gte: 4 }, user: 'Alice', verified: true } } misses $elemMatch, so conditions apply to different elements. { reviews: { $all: [ { rating: { $gte: 4 } }, { user: 'Alice' }, { verified: true } ] } } misuses $all which matches elements individually, not combined. { reviews: { $elemMatch: { rating: 4, user: 'Alice', verified: true } } } uses rating: 4 (exact), not >= 4.
  3. Final Answer:

    { reviews: { $elemMatch: { rating: { $gte: 4 }, user: 'Alice', verified: true } } } -> Option A
  4. Quick Check:

    Use $elemMatch with all conditions and correct operators [OK]
Hint: Combine all conditions inside $elemMatch with correct operators [OK]
Common Mistakes:
  • Omitting $elemMatch causing wrong matches
  • Using exact match instead of comparison operators
  • Using $all which checks elements separately