In mongodb it's easy to make at upsert
, meaning update-or-insert by calling
db.collection.update({criteria}, {updated fields}, true)
The third parameter means - insert a new document if the document doesn't exist yet. So, for example, the following will insert a new document for the user if there's no document for that user yet, and will update it if it already exists:
db.users.update({user_id: '1234'}, {user_id: '1234', name: 'Ran'}, true)
But What If - you want to - not insert a predefined value, but instead - increment a counter? You have a visit_count for each user, and you'd like to increment that count if there's already a document for that user's visit count, or insert 1 if it's the first time. Ideally, you'd like to do something like this:
db.users.update({user_id: '1234'}, {user_id: '1234', $inc: {visit_count: 1}}, true)
Unfortunately, however, mongo doesn't work like this. Mongo does not allow upserts in combination with $inc (or other atomic operations). Atomic operations are nice b/c you're guaranteed that the counter's (in this case counter) value will remain consistent in light of multiple concurrent updates. So how do you make an "increment if the document already exists, and insert if it doesn't"?
Here's the trick I found out yesterday (and to be fair, I'm pretty green to mongo, so maybe there's a better one). Please see the file mongo-insert-or-incr.js below.
This way you're making 2 calls on any increment you want to do. Did you find a way to do this in one call ?