Home > Enterprise >  Update object values inside array where id is equal to inside Array
Update object values inside array where id is equal to inside Array

Time:06-17

Supposedly I want to update the object values of array of a document, but first I will need to look for its id first, heres the structure of document

{
_id: ObjectId('12312')
notifications: [
       {
         _id: ObjectId('1')
          status: 'unread'
       },
       {
         _id: ObjectId('2')
          status: 'unread'
       },
       {
         _id: ObjectId('3')
          status: 'unread'
       }
    ]
}


I want to update the status of notifications under that user where the objectId must be equal to inside the result array

result = 
  [
  new ObjectId("1"),
  new ObjectId("2"),
  ]

this should yield this result after the update

{
_id: ObjectId('12312')
notifications: [
       {
         _id: ObjectId('1')
          status: 'read'
       },
       {
         _id: ObjectId('2')
          status: 'read'
       },
       {
         _id: ObjectId('3')
          status: 'unread'
       }
    ]
}

Heres what Ive done so far but Im not getting the result i need

  const updateuser = await User.updateMany({_id:idofuser, "notifications._id": { $in : result }},{
     $set: {
            "notifications.$.status": "read",
         }
   })

CodePudding user response:

You can use $map to iterate through notifications and use $cond and $mergeObjects to perform the conditional update.

db.collection.update({
  "_id": "12312"
},
[
  {
    "$set": {
      "notifications": {
        "$map": {
          "input": "$notifications",
          "as": "n",
          "in": {
            "$cond": {
              "if": {
                "$in": [
                  "$$n._id",
                  [
                    "1",
                    "2"
                  ]
                ]
              },
              "then": {
                "$mergeObjects": [
                  "$$n",
                  {
                    "status": "read"
                  }
                ]
              },
              "else": "$$n"
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Here is the Mongo Playground for your reference.

  • Related