How to find documents with exactly the same array entries as in a MongoDB query?

To find documents with exactly the same array entries as specified in a MongoDB query, use the $all operator. This operator matches documents where the array field contains all the specified elements, regardless of order.

Syntax

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

Sample Data

db.findDocumentExactlySameInArrayDemo.insertMany([
    {"TechnicalSubjects": ["C++", "Java", "MongoDB"]},
    {"TechnicalSubjects": ["MySQL", "Java", "MongoDB"]},
    {"TechnicalSubjects": ["C#", "Python", "MongoDB"]},
    {"TechnicalSubjects": ["MySQL", "C", "MongoDB"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd69a5f57806ebf1256f12e"),
        ObjectId("5cd69ac057806ebf1256f12f"),
        ObjectId("5cd69ad457806ebf1256f130"),
        ObjectId("5cd69adf57806ebf1256f131")
    ]
}

View All Documents

db.findDocumentExactlySameInArrayDemo.find().pretty();
{
    "_id": ObjectId("5cd69a5f57806ebf1256f12e"),
    "TechnicalSubjects": [
        "C++",
        "Java",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd69ac057806ebf1256f12f"),
    "TechnicalSubjects": [
        "MySQL",
        "Java",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd69ad457806ebf1256f130"),
    "TechnicalSubjects": [
        "C#",
        "Python",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cd69adf57806ebf1256f131"),
    "TechnicalSubjects": [
        "MySQL",
        "C",
        "MongoDB"
    ]
}

Example: Find Documents with Specific Array Elements

Find documents that contain exactly "MySQL", "Java", and "MongoDB" in the TechnicalSubjects array ?

db.findDocumentExactlySameInArrayDemo.find({
    "TechnicalSubjects": { "$all": ["MySQL", "Java", "MongoDB"] }
});
{
    "_id": ObjectId("5cd69ac057806ebf1256f12f"),
    "TechnicalSubjects": ["MySQL", "Java", "MongoDB"]
}

Key Points

  • The $all operator matches arrays that contain all specified elements
  • Order of elements in the query does not matter
  • The array can contain additional elements beyond those specified

Conclusion

Use $all to find documents where an array field contains all specified values. This operator provides flexible matching regardless of element order within the array.

Updated on: 2026-03-15T01:16:32+05:30

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements