Mongo 在更新单个文档时是否确保隔离?

发布于 2025-01-03 22:35:50 字数 778 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扛刀软妹 2025-01-10 22:35:50

首先,正如文档非常清楚地指出的那样

如果您不需要返回文档,则可以使用更新(也可以影响多个文档)。

其次,观看 Update if Current 策略原子页面。它清楚地表明,如果条件适用,则更新就会发生,并且两者之间不会发生任何事情。

First as the documentation very clearly says

If you don't need to return the document, you can use Update (which can affect multiple documents, as well).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文