Is it possible to exclude nested fields in MongoDB with a wildcard?

MongoDBDatabaseBig Data Analytics

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" } } }
raja
Published on 03-Apr-2020 16:53:53
Advertisements