Search code examples
arraysmongodbaggregation-frameworkmongodb-update

How to move MongoDB document fields to an array of objects?


Given a collection of documents similar to the following document

{
    "_id": {
        "$oid": "60582f08bf1d636f4b762ebc"
    }
    "experience": [{
        "title": "Senior Customer Success Account Manager",
        "company": "Microsoft",
        "tenure": 8
    }, {
        "title": "Senior Service Delivery Manager",
        "company": "Microsoft",
        "tenure": 34
    }],
    "company3": "Oracle",
    "tenure3": 10,
    "title3": "Senior Customer Success Manager - EMEA |Oracle Marketing Cloud"
}

How would I write an updateMany or other shell command to move company3, tenure3 and title3 inside the experience array as a new object {company: <company3 value>, title: <title3 value>, tenure: <tenure3 value>} ?


Solution

  • Seems like you're looking for this aggregation update:

    db.collection.update({},
    [
      {
        $set: {
          experience: {
            $concatArrays: [
              "$experience",
              [
                {
                  company: "$company3",
                  title: "$title3",
                  tenure: "$tenure3"
                }
              ]
            ]
          }
        }
      },
      {
        $unset: "company3"
      },
      {
        $unset: "tenure3"
      },
      {
        $unset: "title3"
      }
    ],
    {
      multi: true
    })
    

    Playground: https://mongoplayground.net/p/xoEveE0rdBN