- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Upsert in MongoDB while using custom _id values to insert a document if it does not exist?
You need to use insert() for this. Whenever you insert custom _id values and the document already exist with the custom _id value then an error is visible.
Let us first create a collection with documents. Under this, we tried adding the same document again and this resulted in an error
> db.customIdDemo.insert({"_id":1,"StudentName":"John"}); WriteResult({ "nInserted" : 1 }) > db.customIdDemo.insert({"_id":1,"StudentName":"Carol"}); WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 1.0 }" } }) > db.customIdDemo.insert({"_id":2,"StudentName":"Carol"}); WriteResult({ "nInserted" : 1 }) > db.customIdDemo.insert({"_id":2,"StudentName":"Carol"}); WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 2.0 }" } }) > db.customIdDemo.insert({"_id":3,"StudentName":"Chris"}); WriteResult({ "nInserted" : 1 })
Following is the query to display all documents from a collection with the help of find() method
> db.customIdDemo.find().pretty();
This will produce the following output
{ "_id" : 1, "StudentName" : "John" } { "_id" : 2, "StudentName" : "Carol" } { "_id" : 3, "StudentName" : "Chris" }
Advertisements