Retrieving an embedded object as a document via the aggregation framework in MongoDB?


To retrieve an embedded object as a document, use the aggregation $replaceRoot. Let us first create a collection with documents −

> db.embeddedObjectDemo.insertOne(
   { _id: new ObjectId(),
      "UserDetails": { "UserName": "John", "UserAge": 24, "UserEmailId": "John22@gmail.com" }
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ced580fef71edecf6a1f693")
}
> db.embeddedObjectDemo.insertOne( { _id: new ObjectId(), "UserDetails": { "UserName": "Carol", "UserAge": 26, "UserEmailId": "Carol123@gmail.com" } } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ced5828ef71edecf6a1f694")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ced580fef71edecf6a1f693"),
   "UserDetails" : {
      "UserName" : "John",
      "UserAge" : 24,
      "UserEmailId" : "John22@gmail.com"
   }
}
{
   "_id" : ObjectId("5ced5828ef71edecf6a1f694"),
   "UserDetails" : {
      "UserName" : "Carol",
      "UserAge" : 26,
      "UserEmailId" : "Carol123@gmail.com"
   }
}

Following is the query to retrieve an embedded object as a document via the aggregation framework in MongoDB −

> db.embeddedObjectDemo.aggregate( [
   {
      $replaceRoot: { newRoot: "$UserDetails" }
   }
] );

This will produce the following output −

{ "UserName" : "John", "UserAge" : 24, "UserEmailId" : "John22@gmail.com" }
{ "UserName" : "Carol", "UserAge" : 26, "UserEmailId" : "Carol123@gmail.com" }
raja
Published on 14-Jun-2019 16:37:03
Advertisements