How does the $inc modifier work with concurrent requests in mongodb?

后端 未结 1 934
别那么骄傲
别那么骄傲 2021-01-26 20:12

The $inc modifier can be used to increment a field (such as a counter for analytics, page views etc).

How does it work if there are concurrent requests ?

相关标签:
1条回答
  • 2021-01-26 20:37

    It's a bit broad really but I can offer the broad strokes. As of MongoDB uses collection level locking with the default storage engine. There is also the WiredTiger storage engine available which implements document level locking. But basically in all releases there is some level of "locking" that happens on each request. The finer the level the better depending on your actual throughput needs.

    Essentially no two requests actually happen at the same time since they will "block" on the lock that is made until it is released. So the value that would be returned ( in say a findAndModify() request ), would be as of the "current state" for when that request was made.

    So on such a request the statement that was executed first would return a value of 2, and the next executed statement would return a value of 3. The end position in the database is that the value would presently be 3.

    So there is no way something can "modify" at the same time, and the end state would be that which occurs after "all" requests have been issued. So $inc and other operators do exactly as they should, and modify the content based on the state of the document at the time it was actually able to access it.

    0 讨论(0)
提交回复
热议问题