To do MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update with JavaScript, we use the findAndModify
method.
For instance, we write
db.collection.findAndModify({
query: { _id: "id" },
update: {
$setOnInsert: { foo: "bar" },
},
new: true,
upsert: true,
});
to call findAndModify
with an object with the query
to look for the item with the ID 'id'
.
We set update
to the field on update.
upsert
is set to true
to insert a new entry if the item doesn’t exist.