Is there an "upsert" option in the mongodb insert command?

Since upsert is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upsertsin insert command. It is an option for the update command. If you execute command like below it works as an update, if there is a document matching query, or as an insert with document described by update as an argument.

db.collection.update(query, update, {upsert: true})

MongoDB 3.2 adds replaceOne:

db.collection.replaceOne(query, replacement, {upsert: true})

which has similar behavior, but its replacement cannot contain update operators.


As in the links provided by PKD, db.collection.insert() provides no upsert possibility. Instead, mongo insert inserts a new document into a collection. Upsert is only possible using db.collection.update() and db.collection.save().

If you happen to pass a document to db.collection.insert() which is already in the collection and thus has an _id similar to an existing _id, it will throw a duplicate key exception.