我正在寻找一种在一条指令中更新多个 MongoDB 文档的方法。我知道有一个 updateMany() 查询,但它需要严格的过滤参数才能更新多个文档。
我有一组想要更新的对象,如下所示:
const objectsToUpdate = [
{ _id : 1, field : "a" },
{ _id : 2, field : "b" },
{ _id : 3, field : "c" }
]
该数组基于我从 FTP 服务器检索的文件。我根据数据库检查此文件,如果存在差异则填充它。我可以遍历数组并执行 findOneAndUpdate() 查询,但我必须在任务中处理最多 5000 个文档。
我正在寻找 insertMany() 的更新对应项,其中文档通过 _id 查找并在一个查询中更新。这对 Mongoose 可行吗?
您可以使用bulkWrite https://mongoosejs.com/docs/api.html#model_Model.bulkWrite这会比多个更快updateOne
因为到 MongoDB 只有一次往返。
const bulkOps = objectsToUpdate.map(obj => {
return {
updateOne: {
filter: {
_id: obj._id
},
// If you were using the MongoDB driver directly, you'd need to do
// `update: { $set: { field: ... } }` but mongoose adds $set for you
update: {
field: obj[field]
}
}
}
})
MongooseModel.bulkWrite(bulkOps).then((res) => {
console.log("Documents Updated", res.modifiedCount)
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)