0

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 ?

1
  • Check out the array update operators and arrayFilters. Commented Nov 12, 2021 at 23:22

1 Answer 1

1

use $map in $set

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

mongoplayground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.