Interview Revision
Revision: Querying and Arrays
Operators, nested fields, $elemMatch, sort, limit and pagination in one pass.
IntermediateAbout 6 minutes
- Filter. Sibling keys = AND.
{ city: "Bangalore", isActive: true }. - Operators on the field.
{ age: { $gte: 25, $lt: 40 } }.$innot a pile of$oron one field. - Dot notation.
"address.city". Matching a whole nested object is exact, not partial. - Arrays of scalars.
{ skills: "MongoDB" }= contains. - Arrays of objects. Dotted AND can mix elements. `$elemMatch` when all conditions are the same element (keyboard ₹4500 qty 1, not cable qty 2).
// possibly different line items
db.orders.find({ "items.name": "Mechanical Keyboard", "items.quantity": 2 })
// same element
db.orders.find({
items: { $elemMatch: { name: "Mechanical Keyboard", quantity: 1 } }
})- sort
{ price: 1 }/-1. Compound left to right. Tie-break_idfor pagination. - limit / skip. skip walks n keys — deep pages are a bug. Cursor: range on sort keys + unique
_id. - countDocuments vs estimatedDocumentCount. distinct. Projection
_id: 0. - `$expr` when both sides are fields. `$regex` is not equality on
city.
Interview question
How do you match inside an array of objects?
Think about it first.
Dot notation for one condition. $elemMatch when two or more conditions must hold on the same element. Without it, one item can satisfy name and another quantity.
Interview question
Why can skip() become inefficient?
Think about it first.
skip(n) still traverses n keys every time. Cost grows with page number. Cursor pagination filters after the last key so each page costs about limit.
Practice