Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Retrieving an embedded object as a document via the aggregation framework in MongoDB?
To retrieve an embedded object as a document in MongoDB, use the aggregation framework's $replaceRoot stage. This operator promotes the specified embedded document to the top level, effectively replacing the entire document structure.
Syntax
db.collection.aggregate([
{ $replaceRoot: { newRoot: "$embeddedFieldName" } }
]);
Create Sample Data
db.embeddedObjectDemo.insertMany([
{
"UserDetails": {
"UserName": "John",
"UserAge": 24,
"UserEmailId": "John22@gmail.com"
}
},
{
"UserDetails": {
"UserName": "Carol",
"UserAge": 26,
"UserEmailId": "Carol123@gmail.com"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ced580fef71edecf6a1f693"),
ObjectId("5ced5828ef71edecf6a1f694")
]
}
View Original Documents
db.embeddedObjectDemo.find().pretty();
{
"_id": ObjectId("5ced580fef71edecf6a1f693"),
"UserDetails": {
"UserName": "John",
"UserAge": 24,
"UserEmailId": "John22@gmail.com"
}
}
{
"_id": ObjectId("5ced5828ef71edecf6a1f694"),
"UserDetails": {
"UserName": "Carol",
"UserAge": 26,
"UserEmailId": "Carol123@gmail.com"
}
}
Extract Embedded Objects
db.embeddedObjectDemo.aggregate([
{ $replaceRoot: { newRoot: "$UserDetails" } }
]);
{ "UserName": "John", "UserAge": 24, "UserEmailId": "John22@gmail.com" }
{ "UserName": "Carol", "UserAge": 26, "UserEmailId": "Carol123@gmail.com" }
Key Points
-
$replaceRootcompletely replaces the document structure with the specified embedded object. - The original
_idfield is removed unless explicitly preserved. - Use
$prefix to reference field paths in the aggregation pipeline.
Conclusion
The $replaceRoot aggregation stage effectively extracts embedded objects as standalone documents. This technique is useful for flattening nested data structures and simplifying document output in MongoDB queries.
Advertisements
