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
How to move an array of embedded documents up to parent and change key/value with aggregation pipeline?
Use $replaceRoot in MongoDB aggregation to move array elements up to the parent level and transform key/value pairs. The $replaceRoot stage replaces the input document with a new document structure.
Syntax
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ _id: "$_id" },
{ $arrayToObject: { $map: {
input: "$arrayField",
in: [ "$$this.keyField", "$$this.valueField" ]
}}}
]
}
}
}
]);
Sample Data
db.demo733.insertOne({
"SubjectDetails": [
{
"SubjectName": "MongoDB",
"Marks": 85
},
{
"SubjectName": "MySQL",
"Marks": 90
},
{
"SubjectName": "PL/SQL",
"Marks": 98
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5eac6e6156e85a39df5f6342")
}
Example
Transform the embedded SubjectDetails array into key-value pairs at the parent level ?
db.demo733.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ _id: "$_id" },
{ $arrayToObject: { $map: {
input: "$SubjectDetails",
in: [ "$$this.SubjectName", "$$this.Marks" ]
}}}
]
}
}
}
]);
{
"_id": ObjectId("5eac6e6156e85a39df5f6342"),
"MongoDB": 85,
"MySQL": 90,
"PL/SQL": 98
}
How It Works
-
$maptransforms each array element into a key-value pair using SubjectName as key and Marks as value -
$arrayToObjectconverts the mapped array into an object with dynamic field names -
$mergeObjectscombines the original _id with the transformed object -
$replaceRootreplaces the entire document with the new structure
Conclusion
The $replaceRoot aggregation stage combined with $arrayToObject and $map effectively flattens array structures into parent-level key-value pairs, creating dynamic field names from embedded document values.
Advertisements
