Promote subfields to top level in projection without listing all keys in MongoDB?



To promote subfields to top level in projection, use $objectToArray and $arrayToObject. Let us first create a collection with documents:

> db.promoteSubfieldsDemo.insertOne({'s':10,'y':{'t':20,'u':30,}}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e038004190a577c668b55d5") }

Following is the query to display all documents from a collection with the help of find() method −

> db.promoteSubfieldsDemo.find().pretty();

This will produce the following output −

{    "_id" : ObjectId("5e038004190a577c668b55d5"),    "s" : 10,    "y" : {       "t" : 20,       "u" : 30    } }

Following is the query to promote subfields to top level in projection without listing all keys −

> db.promoteSubfieldsDemo.aggregate([ ...    { "$replaceRoot": { ...       "newRoot": { ...          "$arrayToObject": { ...             "$concatArrays": [ ...                [{ "k": "s", "v": "$s" }], ...                { "$objectToArray": "$y" } ...             ] ...          } ...       } ...    }} ... ]);

This will produce the following output −

{ "s" : 10, "t" : 20, "u" : 30 }
Updated on: 2020-03-27T11:23:46+05:30

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements