Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent access to a document with mongoose

I am writing a web application where more users can perform simultaneous operation in the same document in mongodb. I use the mean.io stack, but I am quite new to it. I was wondering how does mongoose manage concurrency. Every "user click" operation performs first a read to get the document, and a save after some calculations. Of course the sequence read-calculate-save is not atomic. Does mongoose work with 'last change wins' policy, or does it throw a versioning error? Does it make sense in this case to use a queue?

Thanks, best regards.

like image 332
Enrico Avatar asked Jan 20 '14 08:01

Enrico


People also ask

How does Mongoose handle concurrency?

With Optimistic Concurrency The idea behind optimistic concurrency is to track the version of the document and increment the version every time you save() . If the version of the document in the database changed between when you loaded the document and when you save() , Mongoose will throw an error.

Does MongoDB support concurrency?

MongoDB allows multiple clients to read and write the same data. To ensure consistency, MongoDB uses locking and concurrency control to prevent clients from modifying the same data simultaneously.

Which lock in MongoDB provides concurrency?

MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but in MMAPv1, give exclusive access to a single write operation. WiredTiger uses optimistic concurrency control. WiredTiger uses only intent locks at the global, database and collection levels.

What is findById in Mongoose?

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.


1 Answers

Yes the last change will win.

A queue could be a good option to solve the problem but I'll suggest 2 other ways:

  1. You could use more advanced mongodb commands, such as $inc (http://docs.mongodb.org/manual/reference/operator/update/inc/) to compute attomically (if your computation are too complicated maybe it is not possible)
  2. If you don't necessarily need to have the correct count available at any time, you could use a 'big data' approach and just store the raw clicks information. Whenever you need the data (or say every hour or day), you could then use the mongodb aggregate framework, or their mapreduce feature, to compute the correct count.
like image 142
saintmac Avatar answered Oct 08 '22 21:10

saintmac