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
Promote subfields to top level in projection without listing all keys in MongoDB?
To promote subfields to top level in projection without listing all keys in MongoDB, use $replaceRoot with $arrayToObject and $objectToArray operators. This technique flattens nested objects by converting them to arrays and reconstructing them at the root level.
Syntax
db.collection.aggregate([
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": {
"$concatArrays": [
[{ "k": "topLevelField", "v": "$topLevelField" }],
{ "$objectToArray": "$nestedObject" }
]
}
}
}
}
]);
Sample Data
db.promoteSubfieldsDemo.insertOne({
"s": 10,
"y": {
"t": 20,
"u": 30
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e038004190a577c668b55d5")
}
Verify Sample Data
db.promoteSubfieldsDemo.find().pretty();
{
"_id": ObjectId("5e038004190a577c668b55d5"),
"s": 10,
"y": {
"t": 20,
"u": 30
}
}
Example: Promote Subfields to Top Level
db.promoteSubfieldsDemo.aggregate([
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": {
"$concatArrays": [
[{ "k": "s", "v": "$s" }],
{ "$objectToArray": "$y" }
]
}
}
}
}
]);
{ "s": 10, "t": 20, "u": 30 }
How It Works
-
$objectToArrayconverts the nested objectyinto key-value pairs:[{"k": "t", "v": 20}, {"k": "u", "v": 30}] -
$concatArrayscombines the top-level fieldswith the converted nested fields -
$arrayToObjectreconstructs the combined array back into a flat object -
$replaceRootreplaces the document root with the flattened structure
Conclusion
Use $replaceRoot with $arrayToObject and $objectToArray to dynamically promote nested subfields to the top level without explicitly listing each key. This approach automatically flattens any nested object structure.
Advertisements
