0
0
MongoDBquery~5 mins

$all operator for matching all elements in MongoDB

Choose your learning style9 modes available
Introduction

The $all operator helps you find documents where an array contains all the specified values. It is like checking if a basket has all the fruits you want.

You want to find users who have all the skills you list.
You want to find products that have all the features you need.
You want to find orders that include all the items in a shopping list.
You want to find books tagged with all the genres you like.
Syntax
MongoDB
{ field: { $all: [ value1, value2, ... ] } }

The field must be an array in the document.

The query matches documents where the array contains all listed values, in any order.

Examples
Find documents where the tags array contains both "red" and "blue".
MongoDB
{ tags: { $all: ["red", "blue"] } }
Find users who have both "JavaScript" and "Python" in their skills array.
MongoDB
{ skills: { $all: ["JavaScript", "Python"] } }
Find orders where the items array contains all three fruits.
MongoDB
{ items: { $all: ["apple", "banana", "orange"] } }
Sample Program

This example inserts three products with different features. Then it finds products whose features array contains both "waterproof" and "durable".

MongoDB
db.products.insertMany([
  { name: "Product A", features: ["waterproof", "lightweight", "durable"] },
  { name: "Product B", features: ["lightweight", "compact"] },
  { name: "Product C", features: ["waterproof", "durable"] }
])

// Find products that have both "waterproof" and "durable" features
 db.products.find({ features: { $all: ["waterproof", "durable"] } })
OutputSuccess
Important Notes

The $all operator does not care about the order of elements in the array.

If the array in the document is missing any of the specified values, the document will not match.

You can combine $all with other query operators for more complex searches.

Summary

$all matches documents where an array contains all specified values.

It is useful when you want to ensure multiple items are present in an array.

The order of values does not matter for matching.