Get MongoDB documents that contains specific attributes in array

To get MongoDB documents that contain specific attributes in an array, use $and along with dot notation to match multiple field values within the same array field.

Syntax

db.collection.find({
    $and: [
        {"arrayField.attribute1": "value1"},
        {"arrayField.attribute2": "value2"}
    ]
});

Sample Data

Let us first create a collection with documents −

db.demo2.insertMany([
    {
        "StudentInformation": [
            {"StudentName": "John", "StudentAge": 21},
            {"StudentName": "Mike", "StudentAge": 22}
        ]
    },
    {
        "StudentInformation": [
            {"StudentName": "Carol", "StudentAge": 19},
            {"StudentName": "Bob", "StudentAge": 18}
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e08b56e25ddae1f53b62219"),
        ObjectId("5e08b58625ddae1f53b6221a")
    ]
}

Display All Documents

Following is the query to display all documents from the collection −

db.demo2.find().pretty();
{
    "_id": ObjectId("5e08b56e25ddae1f53b62219"),
    "StudentInformation": [
        {
            "StudentName": "John",
            "StudentAge": 21
        },
        {
            "StudentName": "Mike",
            "StudentAge": 22
        }
    ]
}
{
    "_id": ObjectId("5e08b58625ddae1f53b6221a"),
    "StudentInformation": [
        {
            "StudentName": "Carol",
            "StudentAge": 19
        },
        {
            "StudentName": "Bob",
            "StudentAge": 18
        }
    ]
}

Query Documents with Specific Array Attributes

Following is the query to get documents that contain specific attributes in the array −

db.demo2.find({
    $and: [
        {"StudentInformation.StudentName": "Carol"},
        {"StudentInformation.StudentName": "Bob"}
    ]
});
{
    "_id": ObjectId("5e08b58625ddae1f53b6221a"),
    "StudentInformation": [
        {
            "StudentName": "Carol",
            "StudentAge": 19
        },
        {
            "StudentName": "Bob",
            "StudentAge": 18
        }
    ]
}

How It Works

The $and operator ensures that both conditions must be true. Using dot notation StudentInformation.StudentName searches within the array for documents containing students named both "Carol" and "Bob".

Conclusion

Use $and with dot notation to query documents containing multiple specific attributes in arrays. This approach efficiently filters documents where the array contains all specified field values.

Updated on: 2026-03-15T02:09:01+05:30

573 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements