I have a document of the form:
{
"employee_addr": {
"city": "London",
"street": "Downing Street",
"apartment": 10
}
"age": 58,
"name": "Boris"
}
I want to flatten the document. That is, removing the employee_addr nested object and moving its properties to the root of the document.
This document is the result of an aggregation pipeline and I need to add another step to it
How can I do it?
Thanks!
CodePudding user response:
$replaceRoot- Replace the input document with new document.1.1.
$mergeObjects- MergeROOTdocument withemployee_addrobject.$unset- Removeemployee_addrfield.
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
"$employee_addr"
]
}
}
},
{
$unset: "employee_addr"
}
])
CodePudding user response:
One option is using $set if you have only several fields to flatten or you want to flatten an object but not necessarily down to the root:
db.collection.aggregate([
{
$set: {
city: "$employee_addr.city",
street: "$employee_addr.street",
apartment: "$employee_addr.apartment",
employee_addr: "$$REMOVE"
}
}
])
See how it works on the playground example.
Oterwise, use @YongShun answer, which I was about to write, but @YongShun beat me to it :)
