I\'m currently using aggregate operator to return documents that has an array of embedded (sub) documents. I want to rename the field name for the array and also rename fie
There are a couple of approaches to this, but it largely depends on your MongoDB version. More recent versions from 2.6 and upwards support the $map operator which you can use in $project to do what you want:
db.friend.aggregate([
{ "$project": {
"name": 1,
"buddies": {
"$map": {
"input": "$friends",
"as": "el",
"in": {
"nickName": "$$el.name",
"age": "$$el.age"
}
}
}
}}
])
In prior versions you would use $unwind to work with the array elements and re-construct via $group:
db.collection.aggregate([
{ "$unwind": "$friends" },
{ "$group": {
"_id": "$_id",
"name": { "$first": "$name" },
"buddies": {
"$push": {
"nickName": "$friends.name",
"age": "$friends.age"
}
}
}}
])
With the first form being a little more efficient as you are not de-normalizing the array content and producing more documents in the pipeline to process.