Remove all except a single field from a nested document via projection in MongoDB

To remove all except a single field from a nested document in MongoDB, use projection with the find() method. Set unwanted fields to 0 to exclude them, keeping only the desired field visible.

Syntax

db.collection.find(
    {},
    { 
        "nestedDocument.unwantedField1": 0,
        "nestedDocument.unwantedField2": 0
    }
);

Sample Data

db.demo237.insertOne({
    _id: 101,
    Product: {
        description1: { id: 1001 },
        description2: { Name: "Product-1" },
        description3: { Price: 550 }
    }
});
{ "acknowledged": true, "insertedId": 101 }

View Complete Document

db.demo237.find().pretty();
{
    "_id": 101,
    "Product": {
        "description1": {
            "id": 1001
        },
        "description2": {
            "Name": "Product-1"
        },
        "description3": {
            "Price": 550
        }
    }
}

Example: Keep Only description2 Field

To display only the description2 field from the nested Product document ?

db.demo237.find({}, { 
    "Product.description1": 0, 
    "Product.description3": 0 
});
{ "_id": 101, "Product": { "description2": { "Name": "Product-1" } } }

Key Points

  • Setting fields to 0 in projection excludes them from the result.
  • Use dot notation to target specific fields within nested documents.
  • The _id field is included by default unless explicitly excluded with "_id": 0.

Conclusion

Use projection with field exclusion (0) to remove unwanted nested fields. This approach keeps only the desired fields visible while maintaining the document structure.

Updated on: 2026-03-15T02:01:32+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements