Project specific array field in a MongoDB collection?

To project specific fields from an array in MongoDB, use dot notation in the projection document to select only the desired fields from nested array elements. This allows you to return specific fields from array objects while excluding unwanted data.

Syntax

db.collection.find(
    {},
    { 
        "fieldName": 1,
        "arrayField.nestedField": 1
    }
);

Create Sample Data

db.projectionAnElementDemo.insertOne(
    {
        "CustomerId": 100,
        "CustomerDetails": [
            {
                "CustomerName": "Chris",
                "CustomerCountryName": "US"
            },
            {
                "CustomerName": "Robert",
                "CustomerCountryName": "UK"
            }
        ]
    }
);
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd31c56b64f4b851c3a13ea")
}

Display All Documents

db.projectionAnElementDemo.find().pretty();
{
    "_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
    "CustomerId": 100,
    "CustomerDetails": [
        {
            "CustomerName": "Chris",
            "CustomerCountryName": "US"
        },
        {
            "CustomerName": "Robert",
            "CustomerCountryName": "UK"
        }
    ]
}

Project Specific Array Fields

Project only CustomerId and CustomerName from the array ?

db.projectionAnElementDemo.find(
    {},
    {
        CustomerId: 1,
        "CustomerDetails.CustomerName": 1
    }
).pretty();
{
    "_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
    "CustomerId": 100,
    "CustomerDetails": [
        {
            "CustomerName": "Chris"
        },
        {
            "CustomerName": "Robert"
        }
    ]
}

Key Points

  • Use dot notation in projection: "arrayField.nestedField": 1
  • The _id field is included by default unless explicitly excluded
  • All array elements are returned but only with projected fields

Conclusion

MongoDB array field projection uses dot notation to select specific nested fields from array elements. This technique efficiently reduces data transfer by returning only the required fields from complex nested documents.

Updated on: 2026-03-15T01:06:59+05:30

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements