SyntaxStudy
Sign Up
MongoDB Array and Element Operators
MongoDB Beginner 1 min read

Array and Element Operators

MongoDB has specialised operators for querying array fields and for checking field existence and type. The $elemMatch operator matches documents where at least one array element satisfies all specified conditions simultaneously — this is different from querying multiple array conditions at the top level, which can match across different elements. The $all operator requires all specified values to be present in the array. The $size operator matches arrays of an exact length. For field-level checks, $exists tests whether a field is present, and $type filters by BSON type. The $regex operator enables pattern matching on string fields using regular expressions.
Example
// $elemMatch — at least one element must match ALL conditions
db.students.find({
  scores: { $elemMatch: { subject: "math", score: { $gte: 90 } } }
})

// $all — array must contain all specified values
db.posts.find({ tags: { $all: ["mongodb", "nodejs"] } })

// $size — array has exactly N elements
db.users.find({ hobbies: { $size: 3 } })

// $exists — field must be present (or absent)
db.users.find({ deletedAt: { $exists: false } })
db.users.find({ phoneNumber: { $exists: true } })

// $type — filter by BSON type
db.records.find({ value: { $type: "string" } })
db.records.find({ value: { $type: ["int", "double"] } })

// $regex — pattern match on a string field
db.users.find({ email: { $regex: /^alice/i } })

// Dot-notation — query nested document fields
db.users.find({ "address.city": "New York" })

// Query specific array index
db.scores.find({ "grades.0": { $gte: 80 } })