How to move an array of embedded documents up to parent and change key/value with aggregation pipeline?


Use $replaceRoot in MongoDB aggregation. The $replaceRoot replaces the input document with the specified document. The operation replaces all existing fields in the input document, including the _id field. Let us create a collection with documents −

> db.demo733.insertOne(
...    {
...       "SubjectDetails":
...       [
...          {
...             SubjectName:"MongoDB",
...             "Marks":85
...          },
...          {
...             SubjectName:"MySQL",
...             "Marks":90
...          },
...          {
...             SubjectName:"PL/SQL",
...             "Marks":98
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eac6e6156e85a39df5f6342")
}

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

> db.demo733.find();

This will produce the following output −

{ "_id" : ObjectId("5eac6e6156e85a39df5f6342"), "SubjectDetails" : [ { "SubjectName" : "MongoDB", "Marks" : 85 }, { "SubjectName" : "MySQL", "Marks" : 90 }, { "SubjectName" : "PL/SQL", "Marks" : 98 } ] }

Following is the query to move an array of embedded docs up to parent and change key/value with aggregation pipeline −

> db.demo733.aggregate([
...    {
...       $replaceRoot: {
...          newRoot: {
...             $mergeObjects: [
..               . { _id: "$_id" },
...                { $arrayToObject: { $map: { input: "$SubjectDetails", in: [ "$$this.SubjectName", "$$this.Marks" ] } } }
...             ]
...          }
...       }
...    }
... ]).pretty()

This will produce the following output −

{
   "_id" : ObjectId("5eac6e6156e85a39df5f6342"),
   "MongoDB" : 85,
   "MySQL" : 90,
   "PL/SQL" : 98
}

Updated on: 15-May-2020

861 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements