Let’s review another common scenario: posts and votes. Mongo’s approach would be to store vote count in the post itself (caching) and keep voters also in the post, in an array field. Let’s assume we want to register a new vote on post. This operation consists of three steps:
- ensure that the voter hasn’t voted yet, and, if not,
- increment the number of votes and
- add the new voter to the array.
MongoDB’s query and update features allows us to perform all three actions in a single operation. Here’s what that would look like from the shell:
1 2 3
What this says is “get me a story with the given id whose voters array does not contain the given user id and, if you find such a story, perform two atomic updates: first, increment votes by 1 and then push the user id onto the voters array.”
This operation highly efficient; it’s also reliable. The one caveat is that, because update operations are “fire and forget,” you won’t get a response from the server. But in most cases, this should be a non-issue.
quote from MongoDB site.
How would you implement this in your regular SQL database?