Mongoose / MongoDB - 在一条指令中更新具有不同 _id 和值的多个文档

Mongoose / MongoDB - update multiple documents with different _id and values in one instruction

我正在寻找一种在一条指令中更新多个 MongoDB 文档的方法。我知道有一个 updateMany() 查询,但它需要一个严格的过滤器参数才能更新多个文档。

我有一个对象数组,我想像这样更新:

const objectsToUpdate = [
    { _id : 1, field : "a" },
    { _id : 2, field : "b" },
    { _id : 3, field : "c" }
]

该数组基于我从 FTP 服务器检索的文件。我对照数据库检查这个文件,如果有差异就填充它。我可以遍历数组并执行 findOneAndUpdate() 查询,但我必须在一个任务中处理多达 5000 个文档。

我正在寻找 insertMany() 的更新副本,其中文档由 _id 查找并在一个查询中更新。这对 Mongoose 可行吗?

您可以使用 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)
})