- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove all except a single field from a nested document via projection in MongoDB
Set the field you don’t want to include as 0. This would display rest of the values while using find(). Let us first create a collection with documents −
> db.demo237.insertOne({ ... _id:101, ... Product: { ... description1: {id:1001 }, ... description2: {Name:"Product-1" }, ... description3: {Price:550 } ... } ...} ...); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo237.find().pretty();
This will produce the following output −
{ "_id" : 101, "Product" : { "description1" : { "id" : 1001 }, "description2" : { "Name" : "Product-1" }, "description3" : { "Price" : 550 } } }
Following is the query to remove all except a single field from a nested document via projection −
> db.demo237.find({}, { "Product.description1": 0, "Product.description3": 0 });
This will produce the following output −
{ "_id" : 101, "Product" : { "description2" : { "Name" : "Product-1" } } }
- Related Articles
- How to remove all documents from a collection except a single document in MongoDB?
- How to remove a field completely from a MongoDB document?
- Remove only a single document in MongoDB
- How to remove an element from a doubly-nested array in a MongoDB document?
- Display only a single field from all the documents in a MongoDB collection
- MongoDB projection on specific nested properties?
- Selecting only a single field from MongoDB?
- Remove values from a matrix like document in MongoDB
- MongoDB query to remove array elements from a document?
- Updating nested document in MongoDB
- Update only a single document in MongoDB
- Set condition in MongoDB nested document?
- Increment only a single value in MongoDB document?
- MongoDB findOneAndUpdate() to update a single document
- MongoDB query to remove subdocument from document?

Advertisements