Home > Software engineering >  How to update multiple documents with different values in mongoose
How to update multiple documents with different values in mongoose

Time:03-27

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

CodePudding user response:

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}}
      }
   }
] )

CodePudding user response:

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

  • Related