如何执行“减零时删除”与 MongoDB
我在 MongoDB 中有一个文档类型(ErrorTypeOccurences),它只有一个 Name 和 Count 属性。每次记录异常时,我都会递增/递减 Count 属性(以便能够报告应用程序错误类型)。为了进行更新,我发现了如何使用 $inc 修饰符进行更新插入,这很棒,但我正在努力找出一种干净的方法来执行递减操作,如果递减的值等于,该操作也会删除文档零(因为不再存在该类型的错误日志)。
显然,我可以执行递减操作,然后删除计数为零的任何错误文档,但我希望在原子操作中完全在服务器上执行此操作。 findAndModifiy 看起来很有希望,但我不知道如何进行递减更新,然后如果递减计数现在等于零,则有条件地删除记录。
我可以通过标准操作来实现这一点还是需要编写服务器端函数?
我使用的是 C#/NoRM,所以使用它的示例会很棒,但根本不是必需的。谢谢。
I have a document type in MongoDB (ErrorTypeOccurences) that simply has a Name and Count property. I increment/decrement the Count property every time an exception is logged (to be able to report on application error types). For doing updates, I've discovered how to do an upsert with the $inc modifier, which is great, but I'm struggling to figure out a clean way to do a decrement operation that will also delete the document if the decremented value equals zero (since no error logs will exist of that type anymore).
I can obviously do the decrement operation and then remove any error documents whose Count is zero but I'd love to do this in an atomic operation, completely on the server. findAndModifiy looked promising, but I don't see how I could do the decrement update and then conditionally remove the record if it's decremented count was now equal to zero.
Could I achieve this with standard operations or do I need to write a server-side function?
I'm using C#/NoRM, so examples using that would be awesome but not at all required. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须执行两个操作。而且由于 MongoDB 内部没有事务支持,因此您不能保证操作通常会成功。必须添加对应用程序级别的额外检查。
You have to perform two operations. And since there is no transaction support inside MongoDB you can not guarantee that the operation will succeed in general. Additional checks on the application level must be added.
据我所知,您无法立即执行您所要求的操作。您确实希望执行两次更新。这是服务器端功能可以实现的功能。您可以像存储过程一样存储 Javascript 函数。
As far as I know, you cannot do what you are asking out of the box. You are really looking to perform two updates. This is something that a server side function may work for. You can store a Javascript function much like a stored procedure.