0
0
MongodbHow-ToBeginner · 3 min read

How to Use $all Operator in MongoDB for Array Matching

In MongoDB, use the $all operator to find documents where an array field contains all the specified values. It matches documents if the array has every element listed in the $all query 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 structure:

{ field: { $all: [value1, value2, ...] } }

Explanation:

  • field: The name of the array field in the document.
  • $all: The operator that requires all listed values to be present in the array.
  • [value1, value2, ...]: An array of values that must all be found in the document's array field.
json
{
  "field": { "$all": ["value1", "value2", "..."] }
}
💻

Example

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

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

// Query to find documents with tags containing 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 $eq or direct match.
  • Expecting $all to match partial arrays (it requires all listed elements).
  • Confusing $all with $in, which matches if any listed value is present.

Wrong usage example:

{ tags: { $all: "red" } }

This is invalid because $all expects an array of values.

Correct usage:

{ tags: { $all: ["red"] } }
json
{ "tags": { "$all": "red" } } // ❌ invalid

{ "tags": { "$all": ["red"] } } // ✅ valid
📊

Quick Reference

OperatorDescriptionExample
$allMatches arrays containing all specified elements{ tags: { $all: ["red", "blue"] } }
$inMatches arrays containing any of the specified elements{ tags: { $in: ["red", "blue"] } }
$eqMatches arrays exactly equal to the specified array{ tags: { $eq: ["red", "blue"] } }

Key Takeaways

Use $all to match documents where an array contains every specified element.
$all requires an array of values, even if matching a single element.
$all matches regardless of order and allows extra elements in the array.
Do not confuse $all with $in; $in matches any one element, $all matches all.
Use $all for precise multi-value array matching in MongoDB queries.