Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update

Beginning with MongoDB 2.4, it's no longer necessary to rely on a unique index (or any other workaround) for atomic findOrCreate like operations.

This is thanks to the $setOnInsert operator new to 2.4, which allows you to specify updates which should only happen when inserting documents.

This, combined with the upsert option, means you can use findAndModify to achieve an atomic findOrCreate-like operation.

db.collection.findAndModify({
  query: { _id: "some potentially existing id" },
  update: {
    $setOnInsert: { foo: "bar" }
  },
  new: true,   // return new doc if one is upserted
  upsert: true // insert the document if it does not exist
})

As $setOnInsert only affects documents being inserted, if an existing document is found, no modification will occur. If no document exists, it will upsert one with the specified _id, then perform the insert only set. In both cases, the document is returned.


Driver Versions > 2

Using the latest driver (> version 2), you'll use findOneAndUpdate as findAndModify was deprecated. The new method takes 3 arguments, the filter, the update object (which contains your default properties, that should be inserted for a new object), and options where you have to specify the upsert operation.

Using the promise syntax, it looks like this:

const result = await collection.findOneAndUpdate(
  { _id: new ObjectId(id) },
  {
    $setOnInsert: { foo: "bar" },
  },
  {
    returnOriginal: false,
    upsert: true,
  }
);

const newOrUpdatedDocument = result.value;

Its a bit dirty, but you can just insert it.

Be sure that the key has a unique index on it (if you use the _id it's ok, it's already unique).

In this way if the element is already present it will return an exception that you can catch.

If it isn't present, the new document will be inserted.

Updated: a detailed explanation of this technique on the MongoDB Documentation