![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
How to keep two “columns” in MongoDB unique?
Use unique and set it to TRUE. Let us implement the same by creating index and setting two columns to unique −
>db.keepTwoColumnsUniqueDemo.createIndex({"StudentFirstName":1,"StudentLastName":1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
Now you can insert documents in the above collection −
>db.keepTwoColumnsUniqueDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd30fd7b64f4b851c3a13e5") } >db.keepTwoColumnsUniqueDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd30fe5b64f4b851c3a13e6") } >db.keepTwoColumnsUniqueDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":24}); 2019-05-08T22:50:42.803+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: sample.keepTwoColumnsUniqueDemo index: StudentFirstName_1_StudentLastName_1 dup key: { : "John", : "Smith" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: sample.keepTwoColumnsUniqueDemo index: StudentFirstName_1_StudentLastName_1 dup key: { : \"John\", : \"Smith\" }", "op" : { "_id" : ObjectId("5cd30feab64f4b851c3a13e7"), "StudentFirstName" : "John", "StudentLastName" : "Smith", "StudentAge" : 24 } }) WriteError@src/mongo/shell/bulk_api.js:461:48 Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49 Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13 Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21 DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9 @(shell):1:1
Above, since we set the two columns unique and now we are trying to include duplicate values, the following error is visible −
duplicate key error collection
Following is the query to display all documents from a collection with the help of find() method −
> db.keepTwoColumnsUniqueDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd30fd7b64f4b851c3a13e5"), "StudentFirstName" : "John", "StudentLastName" : "Smith", "StudentAge" : 21 } { "_id" : ObjectId("5cd30fe5b64f4b851c3a13e6"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }
Advertisements