如何在猫鼬中更新具有不同值的多个文档

How to update multiple documents with different values in mongoose

我想在单个更新查询中执行以下两个更新。

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

我希望它是这样的:

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

您可以为此使用 MongoDB 的 bulkWrite 方法 - bulkWrite documentation

    await Users.bulkWrite( [
   { updateOne :
      {
         "filter": {_id: id},
         "update": {"$pull": {"friends": requestId}}
      }
   },
   { updateOne :
      {
         "filter": {_id: requestId},
         "update": {"$pull": {"friends": id}}
      }
   }
] )

另一个选项:

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

解释:

$pull 请求的不同用户加入所有条件 $or

playground