Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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" } } }Advertisements