MongoDB query for documents matching array, irrespective of elements order

To query documents matching array elements irrespective of their order in MongoDB, use the $all operator. The $all operator selects documents where an array field contains all the specified elements, regardless of their position or order in the array.

Syntax

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

Sample Data

Let us create a collection with documents containing array fields:

db.demo370.insertMany([
    {
        "Name": "Chris",
        "details": [
            {
                "Subject": "MySQL",
                "CountryName": "US"
            },
            {
                "Subject": "MongoDB",
                "CountryName": "UK"
            }
        ]
    },
    {
        "Name": "David",
        "details": [
            {
                "Subject": "Java",
                "CountryName": "AUS"
            },
            {
                "Subject": "Spring",
                "CountryName": "UK"
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e57e9892ae06a1609a00af0"),
        ObjectId("5e57e9972ae06a1609a00af1")
    ]
}

Display all documents from the collection:

db.demo370.find();
{
    "_id": ObjectId("5e57e9892ae06a1609a00af0"),
    "Name": "Chris",
    "details": [
        { "Subject": "MySQL", "CountryName": "US" },
        { "Subject": "MongoDB", "CountryName": "UK" }
    ]
}
{
    "_id": ObjectId("5e57e9972ae06a1609a00af1"),
    "Name": "David",
    "details": [
        { "Subject": "Java", "CountryName": "AUS" },
        { "Subject": "Spring", "CountryName": "UK" }
    ]
}

Example: Query with $all Operator

Find documents where the details array contains both specified objects, regardless of order:

db.demo370.find({
    details: { $all: [
        { "Subject": "MySQL", "CountryName": "US" },
        { "Subject": "MongoDB", "CountryName": "UK" }
    ]}
});
{
    "_id": ObjectId("5e57e9892ae06a1609a00af0"),
    "Name": "Chris",
    "details": [
        { "Subject": "MySQL", "CountryName": "US" },
        { "Subject": "MongoDB", "CountryName": "UK" }
    ]
}

Key Points

  • The $all operator matches documents where the array contains all specified elements.
  • Order of elements in the array does not matter for matching.
  • The array can contain additional elements beyond those specified in $all.

Conclusion

Use the $all operator to query arrays that contain all specified elements regardless of their order. This operator is particularly useful when you need to match multiple array elements without caring about their position in the array.

Updated on: 2026-03-15T02:42:10+05:30

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements