MongoDB query to get specific list of names from documents where the value of a field is an array

To get specific list of names from documents where the value of a field is an array, use the $all operator. The $all operator selects documents where the array field contains all the specified elements.

Syntax

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

Sample Data

Let us create a collection with documents containing arrays of names ?

db.demo642.insertMany([
    {
        _id: 1,
        ListOfNames: ["Robert", "John"]
    },
    {
        _id: 2,
        ListOfNames: ["Robert", "Chris"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 1,
        "1": 2
    }
}

Display all documents from the collection ?

db.demo642.find();
{ "_id": 1, "ListOfNames": [ "Robert", "John" ] }
{ "_id": 2, "ListOfNames": [ "Robert", "Chris" ] }

Example: Find Documents Containing Specific Names

Find documents where ListOfNames contains both "Chris" and "Robert" ?

db.demo642.find({
    ListOfNames: {
        $all: [ "Chris", "Robert" ]
    }
});
{ "_id": 2, "ListOfNames": [ "Robert", "Chris" ] }

Key Points

  • The $all operator requires all specified elements to be present in the array.
  • Order of elements in the $all array doesn't matter.
  • Only document with _id: 2 matches because it contains both "Chris" and "Robert".

Conclusion

Use the $all operator to query documents where an array field contains all specified values. This is useful for finding documents that match multiple criteria within array fields.

Updated on: 2026-03-15T03:14:52+05:30

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements