0
0
MongoDBquery~5 mins

$elemMatch for complex array queries in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $elemMatch operator do in MongoDB?

The $elemMatch operator finds documents where at least one element in an array matches all the specified query conditions.

Click to reveal answer
intermediate
Why use $elemMatch instead of multiple conditions on an array field?

Because $elemMatch ensures all conditions apply to the same array element, not different elements.

Click to reveal answer
beginner
Example: How to find documents where an array scores has an element with score > 80 and type = 'exam'?
{ scores: { $elemMatch: { score: { $gt: 80 }, type: 'exam' } } }
Click to reveal answer
intermediate
Can $elemMatch be used with nested arrays or objects?

Yes, $elemMatch works with arrays of objects and can match complex conditions inside nested structures.

Click to reveal answer
intermediate
What happens if you use multiple conditions on an array field without $elemMatch?

MongoDB matches documents where each condition applies to any element, possibly different ones, which may give unexpected results.

Click to reveal answer
What does $elemMatch ensure in a MongoDB query?
AAll conditions apply to the same array element
BConditions apply to different array elements
CIt matches only the first element of the array
DIt matches documents without arrays
Which query finds documents where an array tags contains an element with name: 'urgent' and priority: 'high'?
A{ tags: { $elemMatch: { name: 'urgent', priority: 'high' } } }
B{ tags.name: 'urgent', tags.priority: 'high' }
C{ tags: { name: 'urgent' }, tags: { priority: 'high' } }
D{ tags: { $all: ['urgent', 'high'] } }
If you want to find documents where an array has an element with score > 90, which operator is best?
A$in
B$elemMatch
C$gt
D$all
Can $elemMatch be used to query arrays of simple values like numbers?
ANo, it only works with nested arrays
BNo, only for arrays of objects
CYes, and it is required for all array queries
DYes, but usually not needed for simple conditions
What is the risk of not using $elemMatch when querying arrays with multiple conditions?
AQuery will only check the first element
BQuery will fail with syntax error
CConditions may match different elements, causing wrong results
DQuery will return no results
Explain how $elemMatch works in MongoDB and why it is useful for querying arrays.
Think about how multiple conditions relate to one array element.
You got /4 concepts.
    Describe a real-life example where $elemMatch would be necessary to get correct query results.
    Consider a list of products with price and category fields.
    You got /4 concepts.