Question 13 / 50
Must KnowMediumConceptArrays
How do you query a nested field, and when must you use $elemMatch instead of dot notation on an array of objects?
Think about it first.
Short answer
Dot notation for nested fields. On arrays of objects, dot notation can match conditions on different elements. Use $elemMatch when every condition must hold on the same element.
Why?
This is one of the most common correctness bugs in MongoDB. { 'items.price': { $gt: 500 }, 'items.quantity': 2 } matches an order that has some expensive item and some quantity-2 item — not necessarily the same line. $elemMatch requires one element to satisfy the whole predicate.
Example
db.orders.find({ "address.city": "Bangalore" })
db.orders.find({
items: { $elemMatch: { name: "Mechanical Keyboard", quantity: { $gt: 1 } } }
})Interview tip
If the interviewer mentions line items, reach for $elemMatch and say why. It is a fast way to show you have shipped this.
Common mistake
Using $and of dotted paths on an array of objects and believing that implies the same element.
How did you do?