Mongodb如何减少但防止负值

发布于 2025-01-16 09:51:26 字数 342 浏览 4 评论 0原文

我的库存管理应用程序出现问题。我希望它是原子的,因此读取和写入之间没有间隙。

这是我到目前为止发现的:

  • findOneAndUpdate 是原子的,因此读写之间不会有间隙
  • $inc 是原子的,允许我在不知道值的情况下递增/递减值

但是,我想使用 $inc因此,在我的示例中,它会随着减量值或文档的值(如果减去减量值使其为负)而减量。

因此,如果我有一个值为 5 的文档,并以 4 递减,则将其设置为 1。

如果我有一个值为 5 的相同文档,并希望以 6 递减,则将其设置为 0(而不是默认 $ -1)公司行为)。

这是否可能以原子方式实现?

I’m having an issue with my inventory management app. I want it to be atomic, so there’s no gap between read, and write.

Here’s what I’ve found so far:

  • findOneAndUpdate is atomic, so there won’t be a gap between read and write
  • $inc is atomic, and allows me to increment/decrement values without knowing their values

However, I want to use $inc so it decrements in my example with the decrement value, or the document’s value if subtracting the decrement value would make it negative.

So if I have a document with value 5, and decrement with 4, set it to 1.

If I have the same document with value 5, and want to decrement with 6, set it to 0 (as opposed to -1 with default $inc behaviour).

Is this possible somehow in an atomic way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文