Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
0in projection excludes them from the result. - Use dot notation to target specific fields within nested documents.
- The
_idfield 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.
Advertisements
