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!
2
Answers
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:See how it works on the playground example.
Oterwise, use @YongShun answer, which I was about to write, but @YongShun beat me to it 🙂
$replaceRoot
– Replace the input document with new document.1.1.
$mergeObjects
– MergeROOT
document withemployee_addr
object.$unset
– Removeemployee_addr
field.Sample Mongo Playground