Fetch records in MongoDB on querying its subset

To fetch records in MongoDB that contain a subset of values within an array field, use the $all operator. This operator matches documents where the array field contains all the specified elements, regardless of their order or position.

Syntax

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

Sample Data

db.subsetOfAnArrayDemo.insertOne({
    "StudentProgrammingSkills": [
        "Java", "MongoDB", "MySQL", "C++", "Data Structure", 
        "Algorithm", "Python", "Oracle", "SQL Server"
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cb9d1e1895c4fd159f80804")
}

Display All Documents

db.subsetOfAnArrayDemo.find().pretty();
{
    "_id": ObjectId("5cb9d1e1895c4fd159f80804"),
    "StudentProgrammingSkills": [
        "Java",
        "MongoDB", 
        "MySQL",
        "C++",
        "Data Structure",
        "Algorithm",
        "Python",
        "Oracle",
        "SQL Server"
    ]
}

Query for Subset Match

Find documents where the student has both "MongoDB" and "MySQL" skills ?

db.subsetOfAnArrayDemo.find({
    StudentProgrammingSkills: { $all: ["MongoDB", "MySQL"] }
}).pretty();
{
    "_id": ObjectId("5cb9d1e1895c4fd159f80804"),
    "StudentProgrammingSkills": [
        "Java",
        "MongoDB",
        "MySQL", 
        "C++",
        "Data Structure",
        "Algorithm",
        "Python",
        "Oracle",
        "SQL Server"
    ]
}

Key Points

  • The $all operator requires all specified values to be present in the array
  • Order of elements in the $all array doesn't matter
  • Returns the complete document if the subset condition is satisfied

Conclusion

The $all operator is essential for querying documents based on array subsets in MongoDB. It ensures that all specified values exist within the target array field, making it perfect for skill-based or tag-based filtering scenarios.

Updated on: 2026-03-15T00:48:31+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements