[英]How to update multiple documents with different values in mongoose
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
})
You can use MongoDB's bulkWrite method for this - bulkWrite documentation您可以为此使用 MongoDB 的 bulkWrite 方法 - bulkWrite 文档
await Users.bulkWrite( [
{ updateOne :
{
"filter": {_id: id},
"update": {"$pull": {"friends": requestId}}
}
},
{ updateOne :
{
"filter": {_id: requestId},
"update": {"$pull": {"friends": id}}
}
}
] )
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 $pull 请求的不同用户使用 $or 加入所有条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.