MongoDB "$and" operator for subcollection to fetch a document?

When working with MongoDB subcollections (arrays of documents), use $elemMatch combined with $in or $and operators to fetch documents that match specific conditions within array elements.

Syntax

// Using $in for single condition
db.collection.find({
    "arrayField": { 
        "$elemMatch": { 
            "field1": "value1", 
            "field2": { "$in": ["value2"] } 
        } 
    }
});

// Using $and for multiple conditions
db.collection.find({
    "arrayField": { 
        "$elemMatch": { 
            "$and": [
                { "field1": "value1" },
                { "field2": "value2" }
            ]
        } 
    }
});

Sample Data

db.demo83.insertMany([
    {
        "Details": [
            {
                "Name": "Chris",
                "Subject": ["MySQL", "MongoDB"]
            },
            {
                "Name": "David",
                "Subject": ["Java", "C"]
            }
        ]
    },
    {
        "Details": [
            {
                "Name": "Bob",
                "Subject": ["C++", "Python"]
            },
            {
                "Name": "John",
                "Subject": ["Spring", "Hibernate"]
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2bfd2271bf0181ecc422a3"),
        ObjectId("5e2bfd4571bf0181ecc422a4")
    ]
}

Method 1: Using $in with $elemMatch

Find documents where a person named "Chris" studies "MongoDB" ?

db.demo83.find({
    "Details": { 
        "$elemMatch": {
            "Name": "Chris", 
            "Subject": { "$in": ["MongoDB"] }
        }
    }
});
{
    "_id": ObjectId("5e2bfd2271bf0181ecc422a3"),
    "Details": [
        { "Name": "Chris", "Subject": ["MySQL", "MongoDB"] },
        { "Name": "David", "Subject": ["Java", "C"] }
    ]
}

Method 2: Using $and with $elemMatch

Find documents using $and operator for multiple conditions ?

db.demo83.find({
    "Details": { 
        "$elemMatch": { 
            "$and": [
                { "Name": "Chris" },
                { "Subject": "MongoDB" }
            ]
        } 
    }
});
{
    "_id": ObjectId("5e2bfd2271bf0181ecc422a3"),
    "Details": [
        { "Name": "Chris", "Subject": ["MySQL", "MongoDB"] },
        { "Name": "David", "Subject": ["Java", "C"] }
    ]
}

Key Points

  • $elemMatch ensures all conditions match within the same array element.
  • $in checks if a field value exists in a specified array of values.
  • $and requires all specified conditions to be true simultaneously.

Conclusion

Use $elemMatch with $in or $and to query subcollections effectively. $elemMatch ensures conditions match within the same array element, while $in and $and provide flexible matching criteria for complex queries.

Updated on: 2026-03-15T01:52:14+05:30

511 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements