【问题标题】:Efficient multi-document upsert in mongoMongoDB 中高效的多文档 upsert
【发布时间】:2015-05-11 10:03:54
【问题描述】:

我有一个 node.js 应用程序,它可以从远程 API 更新本地 mongo (3.0) 数据存储,我正在努力使其尽可能高效。

集合中的每条记录都有一个唯一的remoteId 属性。调用 API 后,我得到一组记录。然后我应该使用新属性更新本地文档,其中匹配 remoteId 的属性已经存在,在不存在的地方插入,并将本地存在但不在远程数据集中的文档标记为非活动。

我目前的解决方案是这样的(猫鼬代码,为了清晰起见,去掉了回调/承诺,假设它同步运行):

timestamp = new Date
for item in remoteData
  collection.findOneAndUpdate { remoteId: item.remoteId }, { updatedAt: timestamp, /* other properties */ }, { upsert: true }
collection.update { updatedAt: { $lt: timestamp} }, { active: false }, { multi: true }

看起来很简单。但是在处理数以万计的文档时,它会变得很慢。

我查看了 mongo 文档中的 Bulk.upsert,但这似乎仅在您的文档查找查询是静态的时才有效。

我可以在这里做什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    原来我没有完全掌握 mongo Bulk api - 我错过了它基本上是当您调用 execute 时发送到数据库的一组命令。最后,这是我必须做的:

    timestamp = new Date
    bulkOp = collection.initializeUnorderedBulkOp()
    for item in remoteData
      bulkOp.find({ remoteId: item.remoteId }).upsert().updateOne { updatedAt: timestamp, /* other properties */ }
    bulkOp.execute()
    collection.update { updatedAt: { $lt: timestamp} }, { active: false }, { multi: true }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2020-09-06
      相关资源
      最近更新 更多