0

I have this collection

"roomid" : "590ba5386431210c688d07555910cff9cdf7b10bfc309f8d",
"messages": [
      {
        "messagestring": "hello",
        "sender": "590ba5386431210c688d0755",
        "time": "05:21:53",
        "date": "2017-05-23",
        "status": "unread",
        "messageimage": []
      },
      {
        "messagestring": "whatsup",
        "sender": "5910cff9cdf7b10bfc309f8d",
        "time": "05:23:52",
        "date": "2017-05-23",
        "status": "unread",
        "messageimage": []
      }
    ]

I want to update all status "unread" value into "read" value What I did was this code below, but it only update the first status

        Messages.update({roomid: roomid, 'messages.status': 'unread'},
            { '$set':  { 'messages.$.status': 'read' }},
            (err, result) => {
                if (err) {
                  console.log({ error: 'Unable to update status. due to ' + err, });
                } else {
                  console.log(result);
                }
            }
        );

my problem is how will I update all the status field that contains "unread" value into "read" value.

Samip Suwal
  • 1,253
  • 11
  • 17
JerVi
  • 131
  • 3
  • 14
  • There is multi update variant for updating documents in collection, but there is nothing for updating all embedded array documents in a single document. You can get the size of the message array, iterate and updating a single embedded document at a time (Use bulk writes for large arrays) for now. You can track [this](https://jira.mongodb.org/browse/SERVER-27089) jira allowing multiple updates in array. – s7vr May 22 '17 at 22:10
  • sir Veeram, Thank for enlighten, I just thought there is a way to update all embedded array in a sing document, I will read and try your suggestion. thank a lot. – JerVi May 22 '17 at 22:21
  • As stated in the [documentation for the positional `$` operator](https://docs.mongodb.com/manual/reference/operator/update/positional/) *"the positional $ operator acts as a placeholder for the first element that matches the query document"*. See also [SERVER-1243](https://jira.mongodb.org/browse/SERVER-1243). You can always issue the updates looped to either the expected length of the array or until a status response tells you that nothing was matched or updated. – Neil Lunn May 23 '17 at 00:21

0 Answers0