0

Below is my schema:

{  
   "_id":ObjectId("5c49c783de72ec2ec47b95d1"),
   "placement":[  
      {  
         "offer":[  
            {  
               "sent_by":"John",
               "comment":""
            },
            {  
               "sent_by":"Mary",
               "comment":""
            }
         ]
      }
   ]
}

I want to update placement.offer.comment where placement.offer.sent_by is Mary but it always updates the first record. I don't want to provide a hard coded number like placement.0.offer.1.sent_by.

This should be the resulting document:

{  
   "_id":ObjectId("5c49c783de72ec2ec47b95d1"),
   "placement":[  
      {  
         "offer":[  
            {  
               "sent_by":"John",
               "comment":""
            },
            {  
               "sent_by":"Mary",
               "comment":"Some comment updated"
            }
         ]
      }
   ]
}
dnickless
  • 10,733
  • 1
  • 19
  • 34
Sid
  • 1
  • 1
  • Possible duplicate of [Updating a Nested Array with MongoDB](https://stackoverflow.com/questions/23577123/updating-a-nested-array-with-mongodb) – dnickless Jan 29 '19 at 06:09

1 Answers1

0

You would need to use array filters to achieve that:

db.collection.update(
    { /* add additional query filters here */ },
    { $set: { "placement.$[].offer.$[o].comment": "Some updated comment" } },
    { arrayFilters: [ { "o.sent_by": "Mary" } ] }
)
dnickless
  • 10,733
  • 1
  • 19
  • 34