简体   繁体   中英

Update object values inside array where id is equal to inside Array

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",
         }
   })

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM