【问题标题】:MongoDB updateMany in a single operationMongoDB updateMany 在单个操作中
【发布时间】:2022-02-19 09:20:21
【问题描述】:

我对来自猫鼬的updateMany 有一种奇怪的行为。

这里是主要模型:

const Event = {
  user: {ref: 'user'},
  status: String, // one of notProcessed | locked | processed
  ...otherDatas,
}

我有多个 nodeJs 应用程序实例,目标是处理所有事件。这里唯一的限制是为了保持计算的一致性,每个实例必须按插入顺序处理来自特定用户的事件。下面是每个实例的简化代码:

const freeToProcessUser = await Event.findOne({ status: 'notProcessed'})

const updateResult  = await Event.updateMany({ 
  status: 'notProcessed', // this is useful in case a concurrent instance has updated the events in between the two db calls
  user: freeToProcessUser._id
}, { 
  status: 'locked' // update status to lock so another instance cannot process it
})
if (updateInfos.modifiedCount > 0) {
  // all events are now "locked"
  // so here I can process events from this user
}

我使用本地 mongoDb 实例。

问题

问题是,当我启动测试时,我注意到有时,2 个实例有 updateInfos.modifiedCount > 0 !例如,对于特定用户的数据库中的 6 个事件,第一个实例更新 5 个,另一个实例更新 1 个。

当两个实例几乎同时进行更新时会发生这种情况。所以看来两个更新请求都在修改结果...

那么我怎样才能使 updateMany 在一个操作中更新所有文档,这样就不会同时运行其他查询?

希望我已经足够清楚了,如果您需要更多详细信息,请告诉我。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    正如docs 所说:

    When a single write operation (e.g. db.collection.updateMany()) modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic.

    您需要将每个用户的状态嵌入到一个文档中,或者让您的应用程序自动处理用户。

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2021-08-29
      • 2020-03-16
      • 1970-01-01
      • 2011-01-22
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多