6

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.

PrairieProf
  • 174
  • 11
Enrico
  • 364
  • 1
  • 6
  • 11

1 Answers1

6

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.
saintmac
  • 590
  • 4
  • 15
  • Thank you for your reply. It's a very good news for me, because the changes my user do the documents are by design non conflicting (every user changes only his part of the document). – Enrico Jan 20 '14 at 09:14
  • Then make sure that you only update that part of the document, and not retrieve the whole document, and then save the whole document – saintmac Jan 20 '14 at 12:02
  • 1
    It's not entirely true that last wins: http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning – WiredPrairie Jan 20 '14 at 12:16
  • @saintmac good point. When I fetch the document with mongoose, I can decide which fields I need. But what about saving? I thought mongoose only saves the fields that have been changed. Am I wrong? – Enrico Jan 20 '14 at 13:53