Use $elemMatch to find documents where at least one item in an array matches multiple conditions together. It helps when you want to check several things about the same array element.
$elemMatch for complex array queries in MongoDB
Start learning this pattern below
Jump into concepts and practice - no test required
db.collection.find({ arrayField: { $elemMatch: { condition1, condition2, ... } } })$elemMatch applies multiple conditions to the same array element, not different elements.
Without $elemMatch, conditions on array fields check elements independently, which can give wrong results.
db.users.find({ skills: { $elemMatch: { name: "JavaScript", level: { $gte: 3 } } } })db.orders.find({ products: { $elemMatch: { price: { $gt: 100 }, quantity: { $gt: 2 } } } })db.posts.find({ comments: { $elemMatch: { user: "alice", text: /mongodb/i } } })db.addresses.find({ locations: { $elemMatch: { city: "New York", zip: "10001" } } })This inserts three users with different skills. Then it finds users who have at least one skill named "JavaScript" with level 3 or more. It prints the matching users.
db.users.insertMany([
{ name: "John", skills: [ { name: "JavaScript", level: 2 }, { name: "Python", level: 4 } ] },
{ name: "Jane", skills: [ { name: "JavaScript", level: 5 }, { name: "C++", level: 3 } ] },
{ name: "Doe", skills: [ { name: "Java", level: 1 } ] }
])
// Find users with JavaScript skill level 3 or higher
const result = db.users.find({ skills: { $elemMatch: { name: "JavaScript", level: { $gte: 3 } } } }).toArray()
printjson(result)Time complexity: Depends on indexes and array size; using indexes on array fields can speed up queries.
Space complexity: Minimal extra space; query only filters documents.
Common mistake: Forgetting $elemMatch and writing conditions that apply to different array elements separately, causing wrong matches.
Use $elemMatch when you want all conditions to apply to the same array element. Use separate conditions without $elemMatch when conditions can apply to different elements.
$elemMatch helps find array elements matching multiple conditions together.
It ensures all conditions apply to the same element, avoiding false matches.
Use it for complex queries on arrays with multiple criteria.
Practice
$elemMatch operator do in MongoDB queries?Solution
Step 1: Understand array queries
MongoDB arrays can contain multiple elements, and queries may need to check multiple conditions on the same element.Step 2: Role of
$elemMatch$elemMatchensures all conditions apply to the same array element, not spread across different elements.Final Answer:
Finds array elements that match all specified conditions together. -> Option CQuick Check:
$elemMatch= all conditions on one element [OK]
- Thinking $elemMatch matches conditions across different elements
- Confusing $elemMatch with $in or $all
- Assuming $elemMatch updates or deletes elements
scores has an element with score greater than 80 and type equal to 'exam' using $elemMatch?Solution
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.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.Final Answer:
{ scores: { $elemMatch: { score: { $gt: 80 }, type: 'exam' } } } -> Option DQuick Check:
Both conditions inside $elemMatch object [OK]
- Placing some conditions outside $elemMatch
- Using $gt without field name
- Misplacing the type condition outside $elemMatch
{ _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' } } }Solution
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.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.Final Answer:
Only document with _id: 1 -> Option AQuick Check:
Match requires both conditions on same element [OK]
- Matching documents if conditions appear in different elements
- Ignoring the type field condition
- Assuming any element with score > 80 matches
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?
Solution
Step 1: Understand $elemMatch behavior
$elemMatch requires all conditions to be true on the same array element.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.Final Answer:
The fields price and qty are not in the same array element. -> Option BQuick Check:
All conditions must match one element [OK]
- Assuming $elemMatch matches conditions across elements
- Thinking $and replaces $elemMatch for arrays
- Believing MongoDB disallows operators inside $elemMatch
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?Solution
Step 1: Understand the conditions
We want one review element where rating is at least 4, user is 'Alice', and verified is true.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.Final Answer:
{ reviews: { $elemMatch: { rating: { $gte: 4 }, user: 'Alice', verified: true } } } -> Option AQuick Check:
Use $elemMatch with all conditions and correct operators [OK]
- Omitting $elemMatch causing wrong matches
- Using exact match instead of comparison operators
- Using $all which checks elements separately
