- 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 in MongoDB without duplicates
To insert records in MongoDB and avoid duplicates, use “unique:true”. Let us first create a collection with documents.
Here, we are trying to add duplicate records −
> db.insertWithoutDuplicateDemo.createIndex({"StudentFirstName":1},{ unique: true } ); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true }); WriteResult({ "nInserted" : 1 }) > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"David"},{ upsert: true }); WriteResult({ "nInserted" : 1 }) > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true }); WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.insertWithoutDuplicateDemo index: StudentFirstName_1 dup key: { : \"Chris\" }" } }) > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Bob"},{ upsert: true }); WriteResult({ "nInserted" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.insertWithoutDuplicateDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e064405150ee0e76c06a054"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5e064410150ee0e76c06a055"), "StudentFirstName" : "David" } { "_id" : ObjectId("5e06441f150ee0e76c06a057"), "StudentFirstName" : "Bob" }
Advertisements