Find all documents that have two specific id's in an array of objects in MongoDB?

To find all documents that have two specific id's in an array of objects in MongoDB, use the $and operator with dot notation to match multiple values within the same array field.

Syntax

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

Sample Data

db.twoSpecificIdsDemo.insertMany([
    {
        PlayerId: 1,
        "PlayerDetails": [
            {
                id: 100,
                "PlayerName": "Chris"
            },
            {
                id: 101,
                "PlayerName": "Sam"
            },
            {
                id: 102,
                "PlayerName": "Robert"
            },
            {
                id: 103,
                "PlayerName": "Carol"
            }
        ]
    },
    {
        PlayerId: 2,
        "PlayerDetails": [
            {
                id: 104,
                "PlayerName": "Mike"
            },
            {
                id: 105,
                "PlayerName": "Bob"
            },
            {
                id: 102,
                "PlayerName": "Ramit"
            },
            {
                id: 106,
                "PlayerName": "David"
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd3e130edc6604c74817ce4"),
        ObjectId("5cd3e167edc6604c74817ce5")
    ]
}

Example: Find Documents with ID 102 and 103

Find all documents where the PlayerDetails array contains both id 102 and id 103 ?

db.twoSpecificIdsDemo.find({
    $and: [
        { "PlayerDetails.id": 102 },
        { "PlayerDetails.id": 103 }
    ]
}).pretty();
{
    "_id": ObjectId("5cd3e130edc6604c74817ce4"),
    "PlayerId": 1,
    "PlayerDetails": [
        {
            "id": 100,
            "PlayerName": "Chris"
        },
        {
            "id": 101,
            "PlayerName": "Sam"
        },
        {
            "id": 102,
            "PlayerName": "Robert"
        },
        {
            "id": 103,
            "PlayerName": "Carol"
        }
    ]
}

How It Works

The $and operator ensures that both conditions must be satisfied within the same document. Using dot notation "PlayerDetails.id", MongoDB searches through the entire array to match each specified value.

Conclusion

Use $and with dot notation to find documents containing multiple specific values in an array of objects. This approach ensures all specified conditions are met within the same document's array.

Updated on: 2026-03-15T01:09:56+05:30

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements