Mongo Shell update nested array of documents

466 views Asked by At

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": ""
        }
      ]
    }
  }
2

There are 2 answers

0
turivishal On BEST ANSWER
  • $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

0
Tushar Gupta - curioustushar On

Demo - https://mongoplayground.net/p/geb1MRHXNyk

Use update-documents-with-aggregation-pipeline

db.collection.update({},
[
  {
    $set: {
      value: {
        items: { // set item to loop only once
          $map: {
            input: "$value.items", // loop over items
            in: {
              $mergeObjects: [ // merge document
                "$$this",
                { itemName: { $toUpper: "$$this.itemName" } } // change individual itemName to upper
              ]
            }
          }
        }
      }
    }
  }
])

aggregation demo - https://mongoplayground.net/p/9wtSkyjC88c

Demo with your playgroud link - https://mongoplayground.net/p/5J7Qz97gZoJ

update demo with playground link - https://mongoplayground.net/p/8LHEuMakpFF