How to find exact Array Match with values in different order using MongoDB?

To find exact array match with values in different order in MongoDB, use the $all operator combined with $size. The $all operator matches arrays containing all specified elements regardless of order, while $size ensures the exact array length.

Syntax

db.collection.find({
    "arrayField": {
        "$size": exactLength,
        "$all": [value1, value2, value3]
    }
});

Create Sample Data

db.exactMatchArrayDemo.insertMany([
    {
        "StudentName": "David",
        "StudentAge": 22,
        "StudentGameScores": [45, 78, 98]
    },
    {
        "StudentName": "Chris",
        "StudentAge": 23,
        "StudentGameScores": [45, 78]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9c94702d6669774125246c"),
        ObjectId("5c9c94a42d6669774125246d")
    ]
}

View Sample Data

db.exactMatchArrayDemo.find().pretty();
{
    "_id": ObjectId("5c9c94702d6669774125246c"),
    "StudentName": "David",
    "StudentAge": 22,
    "StudentGameScores": [45, 78, 98]
}
{
    "_id": ObjectId("5c9c94a42d6669774125246d"),
    "StudentName": "Chris",
    "StudentAge": 23,
    "StudentGameScores": [45, 78]
}

Case 1: Match Array with 2 Elements

Find documents where StudentGameScores contains exactly [78, 45] in any order ?

db.exactMatchArrayDemo.find({
    "StudentGameScores": {
        "$size": 2,
        "$all": [78, 45]
    }
}).pretty();
{
    "_id": ObjectId("5c9c94a42d6669774125246d"),
    "StudentName": "Chris",
    "StudentAge": 23,
    "StudentGameScores": [45, 78]
}

Case 2: Match Array with 3 Elements

Find documents where StudentGameScores has exactly 3 elements and contains [78, 45] ?

db.exactMatchArrayDemo.find({
    "StudentGameScores": {
        "$size": 3,
        "$all": [78, 45]
    }
}).pretty();
{
    "_id": ObjectId("5c9c94702d6669774125246c"),
    "StudentName": "David",
    "StudentAge": 22,
    "StudentGameScores": [45, 78, 98]
}

Key Points

  • $all matches arrays containing all specified values regardless of order
  • $size ensures the array has the exact length specified
  • Combining both operators creates an exact array match with flexible ordering

Conclusion

Use $all with $size to find exact array matches where element order doesn't matter. The $size operator ensures the exact array length, while $all verifies all specified elements are present.

Updated on: 2026-03-15T00:34:03+05:30

491 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements