skip to Main Content

I want to execute the following two updates in single update query.

// delete the user with (requestID) from friends
await User.updateOne({
    _id: id,
}, {
    $pull: { friends: requestID }
})

// delete the user with (id) from friends
await User.updateOne({
    _id: requestID,
}, {
    $pull: { friends: id }
})

I want it to be like this:

updateMany({
    // delete the user with (requestID) from friends
    // delete the user with (id) from friends
})

2

Answers


  1. You can use MongoDB’s bulkWrite method for this –
    bulkWrite documentation

        await Users.bulkWrite( [
       { updateOne :
          {
             "filter": {_id: id},
             "update": {"$pull": {"friends": requestId}}
          }
       },
       { updateOne :
          {
             "filter": {_id: requestId},
             "update": {"$pull": {"friends": id}}
          }
       }
    ] )
    
    Login or Signup to reply.
  2. Another option:

    db.collection.update({},
    {
     $pull: {
       friends: {
         $or: [
           {
             id: 1
           },
           {
             requestID: 4
           }
         ]
       }
     }
    },
    {
      multi: true
    })
    

    Explained:

    $pull the requested different users joining all conditions with $or

    playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search