Skip to content

Instantly share code, notes, and snippets.

@vanleantking
Forked from rantav/README.md
Created November 5, 2020 04:35
Show Gist options
  • Save vanleantking/a2c923c8846850c881f189ec762aaa63 to your computer and use it in GitHub Desktop.
Save vanleantking/a2c923c8846850c881f189ec762aaa63 to your computer and use it in GitHub Desktop.
MongoDB increment or insert

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.

var id = '1234';
db.users.insert({_id: id, visit_count: 1});
lastError = db.getLastError();
if (lastError) {
// document already exists, so just increment the count
db.users.update({_id: id}, {$inc: {visit_count: 1}})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment