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)