MongoDB query with $all in array

In MongoDB, the $all operator is used to select documents where the value of a field is an array that contains all the specified elements. This operator matches documents where the array field contains every element listed in the $all array, regardless of order or additional elements.

Syntax

db.collection.find({
    "arrayField": { $all: [element1, element2, ...] }
});

Create Sample Data

Let us create a collection with documents containing client details ?

db.demo163.insertMany([
    {
        "ClientDetails": [
            { "ClientName": "Chris" },
            { "ClientName": "David" }
        ]
    },
    {
        "ClientDetails": [
            { "ClientName": "Mike" },
            { "ClientName": "Sam" }
        ]
    },
    {
        "ClientDetails": [
            { "ClientName": "Robert" },
            { "ClientName": "Sam" }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3686d49e4f06af551997c5"),
        ObjectId("5e3686d59e4f06af551997c6"),
        ObjectId("5e3686d59e4f06af551997c7")
    ]
}

Display all documents from the collection ?

db.demo163.find();
{ "_id": ObjectId("5e3686d49e4f06af551997c5"), "ClientDetails": [ { "ClientName": "Chris" }, { "ClientName": "David" } ] }
{ "_id": ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails": [ { "ClientName": "Mike" }, { "ClientName": "Sam" } ] }
{ "_id": ObjectId("5e3686d59e4f06af551997c7"), "ClientDetails": [ { "ClientName": "Robert" }, { "ClientName": "Sam" } ] }

Example: Query with $all Operator

Find documents where ClientDetails array contains both Mike and Sam ?

db.demo163.find({
    "ClientDetails": {
        $all: [
            { "ClientName": "Mike" },
            { "ClientName": "Sam" }
        ]
    }
});
{ "_id": ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails": [ { "ClientName": "Mike" }, { "ClientName": "Sam" } ] }

Key Points

  • The $all operator requires that all specified elements exist in the array field.
  • Order of elements in the $all array doesn't matter.
  • The target array can contain additional elements beyond those specified in $all.

Conclusion

The $all operator is essential for finding documents where an array field contains all specified elements. It ensures complete match validation when you need every listed element to be present in the target array.

Updated on: 2026-03-15T02:25:08+05:30

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements