Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 861
astroanu Avatar asked Nov 14 '13 09:11

astroanu


People also ask

Does MongoDB have Upsert?

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.

Which of them is equivalent of insert in MongoDB?

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.

What does insert do in MongoDB?

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.

What are different ways to insert in MongoDB?

MongoDB provides the following three methods for inserting documents into a database: insert() insertOne() insertMany()


2 Answers

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.

like image 103
zero323 Avatar answered Sep 28 '22 13:09

zero323


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.

like image 24
glormph Avatar answered Sep 28 '22 12:09

glormph