
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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" }
- Related Questions & Answers
- Insert records in MongoDB collection if it does not exist?
- Conditional upsert (multiple insert) when updating document in MongoDB?
- MySQL create user if it does not exist?
- MongoDB query to determine if a specific value does not exist?
- How to create a folder if it does not exist in C#?
- How can I create a directory if it does not exist using Python?
- Create view in MySQL only if it does not already exist?
- How can I create a python directory if it does not exist?
- How to use custom variable while updating a MongoDB document?
- How to delete document by _id using MongoDB?
- Create a table if it does not already exist and insert a record in the same query with MySQL
- Insert array where element does not exist else update it (with multiple conditions)?
- How to check if a table exists in MySQL and create if it does not already exist?
- How to search document in MongoDB by _id
- How to update the _id of a MongoDB Document?
Advertisements