0

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.

1 Answer 1

1

$set

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

mongoplayground

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

2 Comments

I want to update by index positions, not by matching any other field. Is that possible? Because the "text" that you mentioned, I do not have the details of anything else from before, just the index.
I update my answer, you don't need arrayfilters

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.