![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Insert records in MongoDB collection if it does not exist?
You can use update() function to insert records in MongoDB if it does not exist. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.insertIfNotExistsDemo.insertOne({"StudentName":"Mike","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c7eec7b559dd2396bcfbfc2") } > db.insertIfNotExistsDemo.insertOne({"StudentName":"Sam","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c7eec97559dd2396bcfbfc3") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.insertIfNotExistsDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"), "StudentName" : "Mike", "StudentAge" : 21 } { "_id" : ObjectId("5c7eec97559dd2396bcfbfc3"), "StudentName" : "Sam", "StudentAge" : 22 }
Here is the query to insert a record if it does not already exist −
> key = {"StudentName":"David"} { "StudentName" : "David" } > value = {"StudentName":"David","StudentAge":26} { "StudentName" : "David", "StudentAge" : 26 } > db.insertIfNotExistsDemo.update(key, value, upsert=true);
The following is the output −
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("5c7eecd4c743760e97af8261") })
Let us check all documents from a collection. The query is as follows −
> db.insertIfNotExistsDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"), "StudentName" : "Mike", "StudentAge" : 21 } { "_id" : ObjectId("5c7eec97559dd2396bcfbfc3"), "StudentName" : "Sam", "StudentAge" : 22 } { "_id" : ObjectId("5c7eecd4c743760e97af8261"), "StudentName" : "David", "StudentAge" : 26 }
Look at the sample output, the “StudentName”:”David” and “StudentAge”:26 has been inserted successfully.
Advertisements