Categories
JavaScript Answers

How to do MongoDB atomic “findOrCreate”: findOne, insert if nonexistent, but do not update with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *