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?
Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter. In that case, the applied update operation will update the documents. If the value is true and no documents match the condition, this option inserts a new document into the collection.
If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.
insert() In MongoDB, the insert() method inserts a document or documents into the collection. It takes two parameters, the first parameter is the document or array of the document that we want to insert and the remaining are optional. Using this method you can also create a collection by inserting documents.
MongoDB provides the following three methods for inserting documents into a database: insert() insertOne() insertMany()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With