Search code examples
mongodbmongodb-querymongo-shellnested-documents

Mongo Shell update nested array of documents


I try to set an attribute of an document inside an array to uppercase. Here is the link to the mongodb playground https://mongoplayground.net/p/BTP_h3kqK_S

this is a document example

  {
    "_id": ObjectId("5e786a078bc3b3333627341e"),
    "value": {
      "items": [
        {
          "itemName": "alpha305102992",
          "itemNumber": ""
        },
        {
          "itemName": "beta305102630",
          "itemNumber": "P5000"
        },
        {
          "itemName": "gamma305102633 ",
          "itemNumber": ""
        }
      ]
    }
  }

I try to set the "itemName" to upper case.

My desired result would be:

  {
    "_id": ObjectId("5e786a078bc3b3333627341e"),
    "value": {
      "items": [
        {
          "itemName": "ALPHA305102992",
          "itemNumber": ""
        },
        {
          "itemName": "BETA305102630",
          "itemNumber": "P5000"
        },
        {
          "itemName": "GAMMA305102633 ",
          "itemNumber": ""
        }
      ]
    }
  }

Solution

    • $map to iterate loop of value.items array
    • convert itemName to upper case using $toUpper
    • $mergeObjects to merge current object with updated itemName field
    db.collection.update({},
      [{
        $set: {
          "value.items": {
            $map: {
              input: "$value.items",
              in: {
                $mergeObjects: [
                  "$$this",
                  { itemName: { $toUpper: "$$this.itemName" } }
                ]
              }
            }
          }
        }
      }]
    )
    

    Playground