Home > Mobile >  Update multiple array elements by index in a document in MongoDB
Update multiple array elements by index in a document in MongoDB

Time:10-29

I am trying to update multiple elements in an array in a particular document, where I have the indices of the elements that need to be updated.

MongoDB Playground Link

Suppose I have a document:

{
    "key": 1,
    "questions": [
      {
        "text": "first",
      },
      {
        "text": "second",
      },
      {
        "text": "third",
        "answered": "balloon",
      },
    ],
},

I want to update the questions 2 and 3 (by index number) and add key, value pair in the items.
Expected output:

{
    "key": 1,
    "questions": [
      {
        "text": "first",
      },
      {
        "text": "second",
        "answered": "second answer", //Added field
      },
      {
        "text": "third",
        "answered": "third answer", //Updated field
      },
    ],
},

What I have tried so far:

db.collection.update({
  "key": 1,
},
{
  $set: {
    "questions.$[elem0].answered": "second answer",
    "questions.$[elem1].answered": "third answer",
  }
},
{
  arrayFilters: [
    {
      "elem0": 1 //Trying to update index position 1
    },
    {
      "elem1": 2 //Trying to update index position 2
    }
  ],
})

I want the operation to be atomic, instead of multiple queries for each item that I am updating. All the items belong to the nested array of the same document.

CodePudding user response:

$set

db.collection.update({
  "key": 1
},
{
  $set: {
    "questions.1.answered": "second answer",
    "questions.2.answered": "third answer"
  }
})

mongoplayground

  • Related