Mongo 在更新单个文档时是否确保隔离?
Mongo 文档中关于原子性和隔离性的内容有点模糊并且有点令人困惑。我有这个文档结构,我想确保 mongo 能够处理更新,同时隔离来自不同用户的更新。
假设有一系列产品折扣优惠。当用户兑换优惠时,offers_redeemed
字段会递增。 max_allowed_redemptions
字段控制优惠可以兑换的次数。
{
offer_id: 99,
description: “Save 25% on Overstock.com…”
max_allowed_redemptions: 10,
offers_redeemed: 3
}
我使用 findAndModify
对此进行了测试,并且仅当另一次兑换小于或等于允许的最大值时,它才可以通过更新优惠来工作;我想知道这是否是正确的方法,以及这是否适用于多用户、分片环境。是否存在更新 offers_redeemed
会强制超过 max_allowed_redemptions
的情况?显然,这会破坏记录,所以我们需要避免它。
db.offer.findAndModify({
query:{ offer_id: 99, $where: “this.offers_redeemed + 1 <= this.max_allowed_redemptions”},
update: {$inc: {offers_redeemed: 1},
new: true })
The Mongo documentation on atomicity and isolation is a tad vague and slightly confusing. I have this document structure and I want to ensure mongo will handle updates while isolating updated from different users.
Assume a collection of product discount offers. When a user redeems an offer, the offers_redeemed
field is incremented. The max_allowed_redemptions
field controls how many times an offer can be redeemed.
{
offer_id: 99,
description: “Save 25% on Overstock.com…”
max_allowed_redemptions: 10,
offers_redeemed: 3
}
I tested this using findAndModify
and it appears to work by updating the offer only if another redemption would be less than or equal to the max allowed; I want to know if this is the correct way to do it and if this would work in a multi user, sharded environment. Is there a scenario where an update to offers_redeemed
would force it to exceed max_allowed_redemptions
? , obviously, that would corrupt the record so we need to avoid it.
db.offer.findAndModify({
query:{ offer_id: 99, $where: “this.offers_redeemed + 1 <= this.max_allowed_redemptions”},
update: {$inc: {offers_redeemed: 1},
new: true })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,正如文档非常清楚地指出的那样
其次,观看 Update if Current 策略原子页面。它清楚地表明,如果条件适用,则更新就会发生,并且两者之间不会发生任何事情。
First as the documentation very clearly says
Second, watch the Update if Current strategy on the atomic page. It clearly shows that if the condition applies then the update happens and nothing can come between the two.