0
0
MongodbHow-ToBeginner · 3 min read

How to Use $all Operator in MongoDB: Syntax and Examples

In MongoDB, the $all operator is used to find documents where an array field contains all the specified elements. You provide an array of values to $all, and MongoDB returns documents whose array field includes every one of those values, regardless of order or extra elements.
📐

Syntax

The $all operator is used inside a query to match documents where the specified array field contains all the given elements.

Syntax parts:

  • field: The name of the array field to check.
  • $all: Operator that takes an array of values to match.
  • The query returns documents where field contains every element in the $all array.
json
{
  "field": { "$all": ["value1", "value2", "..."] }
}
💻

Example

This example shows how to find documents where the tags array contains both "red" and "blue".

javascript
db.products.insertMany([
  { _id: 1, tags: ["red", "blue", "green"] },
  { _id: 2, tags: ["blue", "yellow"] },
  { _id: 3, tags: ["red", "blue"] },
  { _id: 4, tags: ["green", "yellow"] }
])

// Query to find documents where tags contain both "red" and "blue"
db.products.find({ tags: { $all: ["red", "blue"] } })
Output
[ { _id: 1, tags: ["red", "blue", "green"] }, { _id: 3, tags: ["red", "blue"] } ]
⚠️

Common Pitfalls

Common mistakes when using $all include:

  • Using $all with a single value instead of an array, which will not work.
  • Expecting $all to match documents that contain any one of the values instead of all.
  • Confusing $all with $in, which matches any of the values.
javascript
// Wrong: Using $all with a single value (incorrect)
db.products.find({ tags: { $all: "red" } })

// Right: Use an array even for one value
db.products.find({ tags: { $all: ["red"] } })
📊

Quick Reference

OperatorDescriptionExample Usage
$allMatches arrays containing all specified elements{ tags: { $all: ["red", "blue"] } }
$inMatches arrays containing any of the specified elements{ tags: { $in: ["red", "blue"] } }
$elemMatchMatches arrays with elements matching specified criteria{ tags: { $elemMatch: { $eq: "red" } } }

Key Takeaways

Use $all to find documents where an array contains every specified element.
$all requires an array of values, even if matching only one element.
$all matches all values regardless of order and allows extra elements in the array.
Do not confuse $all with $in; $in matches any one of the values.
Use $all for strict matching of multiple array elements in MongoDB queries.