Query array of subdocuments in MongoDB

To query an array of subdocuments in MongoDB, you can use various operators like $unwind in aggregation pipelines, $elemMatch for matching specific array elements, or simple dot notation for basic queries.

Syntax

// Using $unwind in aggregation
db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $match: { "arrayField.field": "value" } }
]);

// Using $elemMatch
db.collection.find({
    "arrayField": { $elemMatch: { "field": "value" } }
});

Sample Data

db.demo499.insertOne({
    "details": [
        {
            "Name": "MIT",
            "Rank": 1,
            "CountryName": "US"
        },
        {
            "Name": "Stanford University",
            "Rank": 2
        },
        {
            "Name": "University of California, Berkeley",
            "Rank": 3
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e87433d987b6e0e9d18f558")
}

Method 1: Using $unwind (Aggregation)

Use $unwind to flatten the array and then match specific subdocument fields ?

db.demo499.aggregate([
    { $unwind: "$details" },
    { $match: { "details.CountryName": { $exists: true } } },
    { $project: { "details.Name": 1, "details.CountryName": 1, "_id": 0 } }
]);
{ "details": { "Name": "MIT", "CountryName": "US" } }

Method 2: Using $elemMatch

Use $elemMatch to match documents containing array elements that satisfy multiple conditions ?

db.demo499.find({
    "details": { $elemMatch: { "CountryName": { $exists: true } } }
});
{
    "_id": ObjectId("5e87433d987b6e0e9d18f558"),
    "details": [
        { "Name": "MIT", "Rank": 1, "CountryName": "US" },
        { "Name": "Stanford University", "Rank": 2 },
        { "Name": "University of California, Berkeley", "Rank": 3 }
    ]
}

Key Differences

  • $unwind: Flattens arrays and returns individual subdocuments as separate results
  • $elemMatch: Returns the entire document when array contains matching elements

Conclusion

Use $unwind in aggregation pipelines when you need to process individual array elements, or $elemMatch for simple queries that return complete documents containing matching subdocuments.

Updated on: 2026-03-15T03:18:47+05:30

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements