guys. I have an aggregation and a fields map, that I need to rename. Problem is, that the structure is not defined, so I don't really know which attributes will be in resulting output.
In the end, I need to rename fields without removing other ones. Example:
[
...
{
field1: "value1",
field2: "value2",
field3: "value2",
field4: "value4",
}
...
]
For example, I want to rename output field field2 to myNewField. With $project I got:
[$project: {
"myNewField": "$field2"
}]
In this case only myNewField is displayed:
`
[
...
{
myNewField: "value2"
}
...
]
`
Expected result:
[
...
{
field1: "value1",
myNewField: "value2",
field3: "value2",
field4: "value4",
}
...
]
Thank you & have a nice day!
CodePudding user response:
You can add an stage just before the project using $set
to add the new field and into the $project
use the exclusion (0
) with the field you don't want to output:
db.collection.aggregate([
{
"$set": {
"myNewField": "$field2"
}
},
{
"$project": {
"field2": 0
}
}
])
Example here