Suppose I have two documents in a collection:
[
{
"_id": 0,
"name": "aaaa",
"phone": 111
},
{
"_id": 1,
"name": "bbbb",
"phone": 999
}
]
I want to run an aggregation pipeline that will merge/wrap/combine ALL the fields into a top-level root object called lead
. Without mentioning/hardcoding the field names in the query.
Expected output:
[
{
"lead": {
"_id": 0,
"name": "aaaa",
"phone": 111
}
},
{
"lead": {
"_id": 1,
"name": "bbbb",
"phone": 999
}
}
]
2
Answers
Got some help from this answer and was able to achieve it using
$project
:Playground link
$$ROOT
in MongoDB references the content of this document.Works with
$replaceWith
stage to replace the input documents with new outputdocuments. To get each (original) document, you need to use the$$ROOT
variable.Demo @ Mongo Playground