Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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?

2 Answers

0 votes
by (106k points)

MongoDB 3.2 adds replaceOne:

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

It has similar behaviour, but its replacement cannot contain update operators.

0 votes
by (108k points)

db.collection.insert() provides no upsert possibility. Instead, mongo insert will inserts a new document into a collection. Upsert is only possible using db.collection.update() and db.collection.save().

If you carry 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.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...