我和来自猫鼬的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实例。
问题所在
问题是,当我启动测试时,我注意到有时有两个实例有updateInfos.modifiedCount > 0
!例如,对于DB中针对特定用户的6个事件,5由第一个实例更新,1个由另一个实例更新。
当两个实例几乎同时执行更新时,就会发生这种情况。看来两个更新请求都在修改结果.
因此,如何使一个在一个操作中更新所有文档,以便其他查询不能同时运行?
希望我说得够清楚了,如果你需要更多的细节,请告诉我。
发布于 2022-02-19 01:20:21
正如文档所说:
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.
您需要为每个用户将状态嵌入到单个文档中,或者让应用程序原子地处理用户。
https://stackoverflow.com/questions/71178038
复制相似问题