开发者

How to perform a "decrement and delete when zero" with MongoDB

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 pr开发者_如何学Comising, 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜