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

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 27-Mar-2020 15:51:25
Advertisements