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" } } }

Updated on: 03-Apr-2020

684 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements