Search code examples
arraysmongodbmongodb-queryspring-data-mongodb

MongoDB update arrays entry


I have a document to Mongodb update array of objects like this:

    {
    "myArray": [
            {
              "Key1": "string",
              "key2": {
                "entry": "aaa"
              }
            },
            {
              "Key1": "string",
              "key2": {
                "entry": "bbb"
              }
            }
          ]
    }

And I want to modify the key2 field in each object of myArray. The expected result should be :

    {
    "myArray": [
            {
              "Key1": "string",
              "key2Modified":"aaa"
            },
            {
              "Key1": "string",
              "key2Modified":"bbb"
            }
          ]
    }

Any help please ?


Solution

  • use $map in $set

    db.collection.update({},
    [
      {
        $set: {
          "myArray": {
            $map: {
              input: "$myArray",
              as: "a",
              in: {
                Key1: "$$a.Key1",
                key2Modified: "$$a.key2.entry"
              }
            }
          }
        }
      }
    ])
    

    mongoplayground