How to display only the keys from nested MongoDB documents?



Let us create a collection with documents −

> db.demo740.insertOne({ ...    "details": ...    [ ...       { ...          Name:"Chris", ...          Age:21, ...          CountryName:"US" ...       }, ...       { ...          Name:"Bob", ...          Age:20, ...          CountryName:"UK", ...          isMarried:true ...       } ...    ] ... }); {    "acknowledged" : true,    "insertedId" : ObjectId("5ead700c57bb72a10bcf066d") }

Display all documents from a collection with the help of find() method −

> db.demo740.find();

This will produce the following output −

"_id" : ObjectId("5ead700c57bb72a10bcf066d"), "details" : [ { "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "Name" : "Bob", "Age" : 20, "CountryName" : "UK", "isMarried" : true } ] }

Following is the query to get keys of nested MongoDB documents −

> db.demo740.aggregate([ ...    { ...       $project: { ...          ListKeys: { ...             $reduce: { ...                input: "$details", ...                initialValue: [], ...                in: { ...                   $concatArrays: [ ...                      "$$value", ...                      { ...                         $map: { ...                            input: { ...                               $objectToArray: "$$this" ...                            }, ...                            in: "$$this.k" ...                         } ...                      } ...                   ] ...                } ...             } ...          } ...       } ...    } ... ]).pretty()

This will produce the following output −

{    "_id" : ObjectId("5ead700c57bb72a10bcf066d"),    "ListKeys" : [       "Name",       "Age",       "CountryName",       "Name",       "Age",       "CountryName",       "isMarried"    ] }
Updated on: 2020-06-30T07:55:23+05:30

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements