All academies
Roadmap
LEVEL 4 · QUERY OPERATORS

Element & Array Operators

12 min read

Element operators test the shape of a document: $exists checks field presence, $type checks the BSON type.

mongosh
db.users.find({ phone: { $exists: false } })
db.items.find({ qty: { $type: "string" } })  // find bad data!

Array operators

$all requires every listed value to be present; $size matches exact array length; $elemMatch requires a *single element* to satisfy all conditions at once.

mongosh
db.products.find({ tags: { $all: ["wireless", "audio"] } })
db.products.find({ tags: { $size: 2 } })

// one grade element must be both subject math AND score > 90
db.students.find({
  grades: { $elemMatch: { subject: "math", score: { $gt: 90 } } }
})

Why $elemMatch matters

Without it, { "grades.subject": "math", "grades.score": { $gt: 90 } } can match a document where *one* element has subject math and a *different* element has score > 90 — a classic bug.

Regex

$regex (or a /pattern/ literal) performs pattern matching on strings. Anchored prefixes like /^Wire/ can use an index; unanchored patterns cannot.

mongosh
db.products.find({ name: { $regex: "^Wire" } })

Try it yourself

db.products.find({ tags: { $all: ["wireless"] } })
Run in Shell

Check your understanding

Q1.

Which operator ensures a SINGLE array element satisfies multiple conditions?

Q2.

Doc: { tags: ['a', 'b', 'c'] }. Which query does NOT match it?

code
// candidates below
Q3.

A regex anchored with ^ (prefix match) can use an index efficiently.