DocsHub
Querying

Array Operators

Learn how to query documents based on array contents using $all, $elemMatch, and $size.

Array Operators

Arrays are one of the most powerful features in MongoDB. A student can have multiple subjects, a teacher can have multiple qualifications, a course can have multiple enrolled students — all stored as arrays in a single document.

Array operators let you query those arrays precisely:

  • $all — array must contain all specified values
  • $elemMatch — at least one array element must match multiple conditions
  • $size — array must have an exact number of elements

Quick Reminder — Basic Array Queries

Before the operators, remember that you can query arrays without any special operator. MongoDB automatically checks if a value exists anywhere in an array:

// Find students who take Math — no operator needed
db.students.find({ subjects: "Math" })

This works great for a single value. But when you need more control — multiple values, conditions on array elements, or array length — that is when you need array operators.


$all

$all matches documents where an array field contains all of the specified values. The array can have other values too — it just needs to contain at least all the ones you specify.

Syntax

db.collection.find({ field: { $all: [value1, value2, ...] } })

Example — Find students who take both Math AND Physics

db.students.find({
  subjects: { $all: ["Math", "Physics"] }
})

This returns students whose subjects array contains both "Math" and "Physics". A student who only takes Math is not returned. A student who takes Math, Physics, and English is returned.

Example — Find students who take Math, Physics, AND English

db.students.find({
  subjects: { $all: ["Math", "Physics", "English"] }
})

$all vs plain array match

There is an important difference:

// $all — finds documents where subjects contains BOTH values (in any order)
db.students.find({ subjects: { $all: ["Math", "Physics"] } })

// Plain array — finds documents where subjects is EXACTLY this array
db.students.find({ subjects: ["Math", "Physics"] })

The plain array match requires the array to be exactly ["Math", "Physics"] — same values, same order, nothing else. $all is much more flexible and is almost always what you want.

Use $all when you want to find documents that contain multiple specific values in an array. Use a plain value match when you want to find documents that contain a single specific value.


$elemMatch

$elemMatch matches documents where at least one element in an array satisfies all the specified conditions at the same time.

This is the most important array operator to understand correctly.

Why $elemMatch is needed

Imagine each student has an array of grade objects:

{
  name: "Ali Hassan",
  grades: [
    { subject: "Math", score: 88, semester: 1 },
    { subject: "Physics", score: 72, semester: 1 },
    { subject: "English", score: 95, semester: 1 }
  ]
}

Now you want to find students who scored above 90 in Math — both conditions must be true for the same array element.

If you write this without $elemMatch:

// WRONG — this does not work as expected
db.students.find({
  "grades.subject": "Math",
  "grades.score": { $gt: 90 }
})

This query returns students where any grade has subject Math AND any grade has score above 90 — they do not have to be the same grade object. A student with Math at 72 and English at 95 would match — which is wrong.

The correct way:

// CORRECT — both conditions must match the same array element
db.students.find({
  grades: {
    $elemMatch: {
      subject: "Math",
      score: { $gt: 90 }
    }
  }
})

Now MongoDB checks each grade object individually. Both subject: "Math" and score > 90 must be true for the same grade object.

Example — Find students who failed any subject (score below 50)

db.students.find({
  grades: {
    $elemMatch: {
      score: { $lt: 50 }
    }
  }
})

Example — Find students who scored between 80 and 95 in Physics

db.students.find({
  grades: {
    $elemMatch: {
      subject: "Physics",
      score: { $gte: 80, $lte: 95 }
    }
  }
})

$elemMatch with simple arrays

$elemMatch also works on arrays of plain values — but for a single condition it is simpler to use the direct match:

// These return the same result
db.students.find({ subjects: "Math" })
db.students.find({ subjects: { $elemMatch: { $eq: "Math" } } })

Use $elemMatch on simple arrays only when you have multiple conditions on the same element — otherwise the direct match is cleaner.


$size

$size matches documents where an array field has an exact number of elements.

Syntax

db.collection.find({ field: { $size: number } })

Example — Find students with exactly 3 subjects

db.students.find({ subjects: { $size: 3 } })

Example — Find students with exactly 1 subject

db.students.find({ subjects: { $size: 1 } })

Example — Find courses with exactly 0 enrolled students

db.courses.find({ enrolledStudents: { $size: 0 } })

$size limitation — no ranges

$size only works with an exact number. You cannot do { $size: { $gt: 2 } } to find arrays with more than 2 elements — that is not supported.

// This does NOT work
db.students.find({ subjects: { $size: { $gt: 2 } } })

To find documents where an array has more than a certain number of elements, use the index existence trick:

// Find students with at least 3 subjects
// Check if the element at index 2 exists (0-based index)
db.students.find({ "subjects.2": { $exists: true } })

If subjects.2 exists, the array has at least 3 elements.

The index trick works because MongoDB arrays are zero-indexed. subjects.0 is the first element, subjects.1 is the second, subjects.2 is the third. If subjects.2 exists, the array has at least 3 items.


School System Examples

// Students who take both Math and Physics
db.students.find({
  subjects: { $all: ["Math", "Physics"] }
})

// Students who take Math, Physics, and English — all three
db.students.find({
  subjects: { $all: ["Math", "Physics", "English"] }
})

// Students with exactly 2 subjects
db.students.find({
  subjects: { $size: 2 }
})

// Students with at least 3 subjects
db.students.find({
  "subjects.2": { $exists: true }
})

// Students who scored above 90 in Math
db.students.find({
  grades: {
    $elemMatch: {
      subject: "Math",
      score: { $gt: 90 }
    }
  }
})

// Students who failed any subject
db.students.find({
  grades: {
    $elemMatch: {
      score: { $lt: 50 }
    }
  }
})

// Students who scored between 80 and 95 in any subject in semester 1
db.students.find({
  grades: {
    $elemMatch: {
      score: { $gte: 80, $lte: 95 },
      semester: 1
    }
  }
})

// Students who have exactly no grades recorded yet
db.students.find({
  grades: { $size: 0 }
})

Quick Reference

OperatorWhat it doesExample
$allArray contains all specified values{ subjects: { $all: ["Math", "Physics"] } }
$elemMatchOne array element matches all conditions{ grades: { $elemMatch: { score: { $gt: 90 } } } }
$sizeArray has exact number of elements{ subjects: { $size: 3 } }

The most common mistake with array queries is forgetting to use $elemMatch when querying arrays of objects with multiple conditions. If you query "grades.subject" and "grades.score" separately, MongoDB does not guarantee both conditions apply to the same array element. Always use $elemMatch when you need multiple conditions on the same object inside an array.

On this page