1

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 Answer 1

1

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" } ]}
)
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.