Array Operators

MongoDB provides specialized operators for querying documents that contain arrays.

1. $all

Matches arrays that contain all the specified elements (regardless of order).

// Find items where the tags array contains both "appliance" and "school"
db.products.find({ tags: { $all: ["appliance", "school"] } })

2. $elemMatch

The `$elemMatch` operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

// Find documents where at least one array element matches both criteria
db.survey.find({
  results: {
    $elemMatch: { product: "xyz", score: { $gte: 8 } }
  }
})

3. $size

The `$size` operator matches any array with the number of elements specified by the argument.

// Find documents where the tags array has exactly 3 elements
db.products.find({ tags: { $size: 3 } })

4. Querying an Array for an Element

To query if an array contains at least one element with a certain value, you don't need a special operator.

// Find products where one of the tags is "red"
db.products.find({ tags: "red" })
Note: You cannot use `$size` to find a range of array sizes (e.g., $size: { $gt: 5 }). For range queries on array lengths, you might need an alternative strategy like storing the length in a separate field.