How to update all all nested array with condition in MongoDB

Viewed 42

I have an array with nested objects. If the message is "Hi", I want to change it to "Hello". Here is my array:

[{
  name : "name",
  email : "email",
  conversation : [
  {
    message : "Hi",
    seenBy : "karen"
  },
  {
    message : "Hi",
    seenBy : "leo"
  },
  {
    message : "Goodbye",
    seenBy : "mark"
  }
 ]
},
{
  name : "name",
  email : "email",
  conversation : [
  {
    message : "Hi",
    seenBy : "karen"
  },
  {
    message : "Listen",
    seenBy : "leo"
  },
  {
    message : "Sit",
    seenBy : "mark"
  },
{
    message : "Hi",
    seenBy : "mark"
  }
 ]
}]

Here's have I have tried:

db.updateMany({ conversation: { $elemMatch: { message: "Hi" } } },
  { $set: {"items.$[].message": "Hello" }},
  {multi: true}
  )

But it updates all messages to "Hello" even messages that are not "Hi"

1 Answers

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

Use $[<identifier>]

The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation,

db.collection.update(
  {conversation: { $elemMatch: { message: "Hi" } } },
  { $set: { "conversation.$[c].message": "Hello" } },
  { multi: true, arrayFilters: [ { "c.message": "Hi" } ]}
)
Related