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?

- 3,901
- 2
- 36
- 50
-
2Google "mongodb upsert", bang the 3rd result :) [docs.mongodb.org/manual/reference/method/db.collection.update](http://docs.mongodb.org/manual/reference/method/db.collection.update) – Rituparna Kashyap Nov 14 '13 at 12:52
3 Answers
Since upsert
is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upserts
in 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.

- 322,348
- 103
- 959
- 935
-
2Apart from update, db.collection.save() also provides and upsert possibility. – glormph Nov 14 '13 at 10:17
-
2It is translated to `this.update( { _id : obj._id } , obj , true )` if `typeof( obj._id ) != "undefined"` but it is nothing more than a wrapper. – zero323 Nov 14 '13 at 10:25
-
-
@AbdulHameed True. From the looks I am pretty sure it was copied from Python session :) Corrected, thanks. – zero323 May 28 '16 at 06:58
-
Won't this update the document that exists(if it exists) with the new document? – basickarl Oct 30 '16 at 18:25
-
2What do you mean "its replacement cannot contain update operators"... a replacement is a document value, how could it *ever* contain operators? – Noldorin Sep 21 '17 at 00:41
-
In python it is `True` but in Mongo shell it is `true`. In Mongo there is no `bool` like `True`. – WesternGun Jan 16 '18 at 21:02
-
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.

- 994
- 6
- 13
-
Thanks. As the doc explains upsert is only supported for update and save – astroanu Nov 14 '13 at 11:23
For upserting a singe document using the java driver:
FindOneAndReplaceOptions replaceOptions = new FindOneAndReplaceOptions();
replaceOptions.upsert(true);
collection.findOneAndReplace(
Filters.eq("key", "value"),
document,
replaceOptions
);
Although uniqueness should be ensured from Filters.eq("key", "value")
otherwise there is a possibility of adding multiple documents. See this for more

- 2,463
- 2
- 32
- 48