Mongodb如何减少但防止负值
我的库存管理应用程序出现问题。我希望它是原子的,因此读取和写入之间没有间隙。
这是我到目前为止发现的:
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论