【问题标题】:How to perform Bulk Upsert如何执行批量 Upsert
【发布时间】:2020-10-13 15:56:02
【问题描述】:

我正在尝试对文档执行批量更新插入。我知道这不能在 Meteor:Mongo 中本地完成,Node MongoDB 库必须与 rawCollection 一起使用。

我有以下

const bulkUpserts = [];
for (let doc of docs) {

  bulkUpserts.push({
    updateOne: {
      filter: {
        fizz: doc.buzz
      },
      update: doc,
      upsert: true,
      setOnInsert: {
        "foo": "bar",
        "createdBy": Meteor.userId(),
        "createdDate": new Date()
      }
    }
  });
}

Collection.rawCollection().bulkWrite(bulkUpserts);

^ 的问题是setOnInsert 似乎不起作用。我的foos 没有设置。看起来setOnInsert 不能作为updateOne 的选项使用。什么是替代方案?令人惊讶的是,我还没有找到在 Meteor 中执行此操作的方法。

谢谢!

【问题讨论】:

  • 我没有使用过bulkWrite,但我已经能够使用updateMany (docs.mongodb.com/manual/reference/method/…) 完成您描述的任务。这对你来说是一个选择吗?如果是这样,那么我可以发布一个示例。
  • 嘿 Christian,我在另一个 Node 应用程序中使用 bulkWrite 非常好。但我最终使用了下面的内容

标签: javascript node.js mongodb meteor


【解决方案1】:

我最终使用了

const bulk = LineItems.rawCollection().initializeUnorderedBulkOp();

for (let doc of docs) {    
  bulk.find({
    fizz: doc.buzz
  }).upsert().updateOne({
    $set: doc,
    $setOnInsert: {
      _id: Random.id(),
      "foo": "bar",
      "createdBy": Meteor.userId(),
      "createdDate": new Date()
    }
  });
}
bulk.execute().then().catch(error => console.error(error));

【讨论】:

    猜你喜欢
    • 2014-07-17
    • 1970-01-01
    • 2016-12-30
    • 2021-01-07
    • 1970-01-01
    • 2014-11-15
    • 2016-04-19
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多