mongodbmongodb-queryaggregation-frameworkpymongo

Create array of elements based on another existing array using MongoDB Aggregation


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?


Solution

  • 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"
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground