- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Is it possible to exclude nested fields in MongoDB with a wildcard?
Achieve this with aggregation pipeline. Let us first create a collection with documents −
> db.demo413.insertOne( ... { ... "_id": "101", ... "details": { ... "Info1": { ... Name:"Chris", ... Age:21 ... }, ... "Info2": { ... Name:"David", ... Age:23 ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : "101" }
Display all documents from a collection with the help of find() method −
> db.demo413.find();
This will produce the following output −
{ "_id" : "101", "details" : { "Info1" : { "Name" : "Chris", "Age" : 21 }, "Info2" : { "Name" : "David", "Age" : 23 } } }
Following is the query to exclude nested fields −
> db.demo413.aggregate([ ... { $project: { "details" : { $objectToArray: "$details" } } }, ... { $project: { "details.v.Age" : 0} }, ... { $project: { "details" : { $arrayToObject: "$details"} } } ... ]);
This will produce the following output −
{ "_id" : "101", "details" : { "Info1" : { "Name" : "Chris" }, "Info2" : { "Name" : "David" } } }
Advertisements