Search code examples
mongodbmongoose

How to update the value of array object property with another filed value of the same array object in MongoDB


In the below restaurant object, I would like to update the addons property of the optionalAddons object with the value of addableIngredients. How can I do so for each restaurant and each item?

  "name": "4Cheeze",
  "items": [
    {
      "name": "Chicken Grill",
      "addableIngredients": "cheese - 2, mayo - 0",
      "optionalAddons": {
        "addable": 10,
        "addons": ''
      }
    },
    {
      "name": "Fried Momo",
      "addableIngredients": "cheese - 2, mayo - 0",
      "optionalAddons": {
        "addable": 10,
        "addons": ''
      }
    },
  ],
}

Here is the Mongo playground link to play with: https://mongoplayground.net/p/JVjV2AiocHD


Solution

  • One option is to use an update with a pipeline to push the current value of addableIngredients into the existing array:

    db.collection.updateMany({},
    [
      {$set: {items: {$map: {
              input: "$items",
              in: {$mergeObjects: [
                  "$$this",
                  {optionalAddons: {addons: {
                        $mergeObjects: [
                          "$$this.optionalAddons",
                          {addons: {$concatArrays: [
                                "$$this.optionalAddons.addons",
                                ["$$this.addableIngredients"]
                           ]}}
                        ]
                  }}}
              ]}
      }}}}
    ])
    

    See how it works on the playground example