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": "[email protected]" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ced580fef71edecf6a1f693") } > db.embeddedObjectDemo.insertOne( { _id: new ObjectId(), "UserDetails": { "UserName": "Carol", "UserAge": 26, "UserEmailId": "[email protected]" } } ); { "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" : "[email protected]" } } { "_id" : ObjectId("5ced5828ef71edecf6a1f694"), "UserDetails" : { "UserName" : "Carol", "UserAge" : 26, "UserEmailId" : "[email protected]" } }
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" : "[email protected]" } { "UserName" : "Carol", "UserAge" : 26, "UserEmailId" : "[email protected]" }