Skip to content

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 } }. $in not a pile of $or on 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 } }
})
The $elemMatch question
  • sort { price: 1 } / -1. Compound left to right. Tie-break _id for 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.

Interview question

Why can skip() become inefficient?

Think about it first.

Practice