1

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 ?

Say I have the document:

{ "views" : 1 }

What happens if there are two concurrent requests using $inc ? Will views be 2 or 3 ?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190

1 Answers1

5

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • Neil, if 1000 view my article at the same time and I $inc views on each request does this line them up one after another creating a bottle neck or does this do a better job than that ? – GaddMaster May 17 '22 at 08:20