Get fields from multiple sub-documents that match a condition in MongoDB?

To get fields from multiple sub-documents that match a condition in MongoDB, use the aggregation pipeline with $unwind to flatten nested arrays, $match to filter documents, and $project to select specific fields.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $match: { "arrayField.nestedField": "condition" } },
    { $project: { fieldName: "$arrayField.targetField" } }
]);

Sample Data

db.demo671.insertOne({
    "details": [
        {
            "id": "1"
        },
        {
            "CountryName": "US",
            "details1": [
                { "id": "1" },
                { "id": "2" }
            ]
        },
        {
            "CountryName": "UK",
            "details1": [
                { "id": "2" },
                { "id": "1" }
            ]
        },
        {
            "CountryName": "AUS",
            "details1": [
                { "id": "1" }
            ]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ea3e5d004263e90dac943e0")
}

View Sample Data

db.demo671.find();
{
    "_id": ObjectId("5ea3e5d004263e90dac943e0"),
    "details": [
        { "id": "1" },
        { "CountryName": "US", "details1": [{ "id": "1" }, { "id": "2" }] },
        { "CountryName": "UK", "details1": [{ "id": "2" }, { "id": "1" }] },
        { "CountryName": "AUS", "details1": [{ "id": "1" }] }
    ]
}

Example: Extract Countries with Specific ID

Get country names from sub-documents where nested details1 contains id = "1" ?

db.demo671.aggregate([
    { $unwind: '$details' },
    { $match: { 'details.details1.id': '1' } },
    { $project: { _id: 0, Country: '$details.CountryName' } }
]);
{ "Country": "US" }
{ "Country": "UK" }
{ "Country": "AUS" }

How It Works

  • $unwind creates separate documents for each array element in "details"
  • $match filters documents where nested "details1" array contains id = "1"
  • $project extracts only the CountryName field and renames it to "Country"

Conclusion

Use $unwind to flatten nested arrays, then apply $match for filtering and $project for field selection. This pipeline approach efficiently extracts specific fields from multiple sub-documents based on conditions.

Updated on: 2026-03-15T03:27:46+05:30

732 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements