I need to take a field from a document as input, like below:
"participants": ["John", "Peter"],
and make the output field like that:
"participants": [
{
"name": null,
"identifier": "John",
"type": "individual",
},
{
"name": null,
"identifier": "Peter",
"type": "individual",
},
]
Basically, the idea is get every element of an array and "replace it" by a structure/map with multiple fields.
I tried to do it by unwinding the participants field and regrouping everything pushing the field inside the new structure, but certainly there's a better way to do it... Right?
Use $map
to iterate through the array and augment the entries, in an update with aggregation pipeline.
db.collection.update({},
[
{
"$set": {
"participants": {
"$map": {
"input": "$participants",
"as": "p",
"in": {
"name": null,
"identifier": "$$p",
"type": "individual"
}
}
}
}
}
])