MongoDB multiple simultaneous accesses to one document

2.9k views Asked by At

I am building a social network app and I am very concerned about next thing.What happens when in mongoDB a lot of users(let's assume millions) try to modify the same document at the same time. Will there be any mismatch ,or ignored queries or any kind of unexpected behaviour?

Practical Example: 2 collections: 'posts' and 'likes' posts will have fields id | name | info | numberOfLikes likes will have fields id | post | fromUser

When assumed millions of users like the post ,like object appears in 'likes' collection and business logic automatically increments numberOfLikes for post. I thought if there could be a conflict when tons of users try to modify that post likes count at the same time.

3

There are 3 answers

1
davsp On BEST ANSWER

Databases have mechanisms in place to prevent this kind of situation. You can 'lock' on various logical structures, so you can be assured your data is intact - regardless of your transaction count.

See more below:

http://docs.mongodb.org/manual/faq/concurrency/

0
jianfyun On

In MongoDB, operations are atomic at the document level. See http://docs.mongodb.org/manual/core/data-modeling-introduction/#atomicity-of-write-operations

2
CodeCaster On

A couple of things.

You're saying you're building a social app and expect millions of likes and "tons" of them at the same time. Of course it's good to consider performance and scaling at the start of a project, but you're not going to build the next Facebook right now.

Furhtermore, you seem to want to use MongoDB as primary database for this app, and you seem to want to use it as a relational database. Read the somewhat biased titled article Why You Should Never Use MongoDB.

I'd suggest backing your site with a relational database (which may also be better for queries like "What posts did this user like" and "Did this user already like this post") and denormalizing that into MongoDB at regular intervals.