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

astroanu picture astroanu · Nov 14, 2013 · Viewed 86.5k times · Source

I know this may be a silly question, but I read on an e-book that there is an upsert option in MongoDB insert. I couldn't find proper documentation about this. Can someone educate me about this?

Answer

zero323 picture zero323 · Nov 14, 2013

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.