EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Unique
Secondary Sidebar
MongoDB Tutorial
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

MongoDB Unique

By Sulaksh MoreSulaksh More

MongoDB Unique

Introduction to MongoDB Unique

MongoDB’s Unique Constraint makes certain that the fields indexed in it, do not store duplicate values for the same field, i.e., making sure the uniqueness of fields. By default, MongoDB enforces this unique constraint on the “_id” field, while inserting new data. One of the major responsibilities is to ensure no duplicate data has been stored in a single key. We also have restrictions here, like MongoDB will be unable to establish a unique index on any specific field, in case if the collection somehow has already stored any data that would breach the feature of unique constraint for the index.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Now that we have understood what Unique Constraint in MongoDB, let us learn the standard syntax to write this Unique method.

db.collection_name.createIndex( {field_name : 1} , {unqiue : true} )

Explanation: Now, as you can see in the above syntax, we have created a simple index, which means the data stored in the collection will be indexed and adding the argument with “{unqiue: true}” implements the unique constraint.

How UNIQUE Constraint works in MongoDB?

The Unique Index allows the insertion and storing of the values in a document into a collection IF there is no other document in the same collection with the same index key and value. The unique constraint can be implemented on compound indexes. This helps MongoDB to implement uniqueness when combining the index key values.  Unique Constraint over separate multiple documents is possible in MongoDB, and it is an essential function in avoiding storing of same values for the indexed key in a different document.

Unique Constraint in MongoDB will allow only a single document with the same value for the indexed key. If we attempt to insert the same value for a single indexed key, it will result in an error.

Query #1

db.code.find()

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (85,992 ratings)

This returns every document in the collection.

Query #2

db.code.insert( { name:”kumar”, city:“Pune”, code:19 } )

This is an attempt to insert a record with the same code.

Code:

db.code.find()

Output:

MongoDB Unique - 1

Explanation: Here, we have implemented the unique index for “code” key, and so when we try to store a document with existing code, it results in “duplicate key error”.

Unique Constraint for Null Value

When we store any document, we store values for the respective keys, and it is stored as per indexing. But in case, if we attempt to store a document that has no specific value or data for a key, for any uncertain key, the document will be stored, and the empty value will be stored as a null value in that document.  In MongoDB, only on the document is allowed to be stored with a single index field missing.

Examples to Implement UNIQUE Constraint in MongoDB

Implementing Unique Contraint on separate documents to not store the same value for the indexes key, in two different documents.

Example #1

We will attempt to insert and store documents with duplicate values. We have a collection named educba, which we will check with find method: db.educba.find()

Code:

db.educba.find()

Output:

store documents

As you can see in the above image, we have a collection named educba, and the document has one default unique “_id” and two more keys. We will now implement the unique constraint on the “Name”, which will make it unique, duplicate insertion proof.

Code:

db.educba.createIndex( { “Name” : 1 } , { unique : true } )

Output:

createIndex

Using >db.educba.createIndex( { “Name”:1 ,{ unique: true} ) we have implemented the unique constraint of the Name key. In return message we have “ok” and other details. Now let us attempt to insert a single new document and then reinsert it with the same value. Refer to the below screenshot for the proper output.

Code:

db.educba.insert({ Name : "Sulaksh" ,  City : "Pune" })

Output:

successfully inserted

First Query:db.educba.insert({ Name : "Sulaksh" ,  City : "Pune" })

The above query will be successfully inserted.  Then we attempted to insert the same query, i.e. same document with the same values, but it resulted in an error that states, “terms”: “E11000 duplicate key error collection: test.educba index: Name_1 dup key: { : \”Sulaksh\” }””. This makes our unique constraint applied over the Name field successfully.

Example #2

We will now implement the unique value constraint on Key, which holds Email Values. We will update our documents to add another field with emails. We will then add another index on the field of emails, in order not to store the same email id for multiple documents.

Code:

db.educba.createIndex( {email : 1},{unique : true} )

Output:

not attempt to insert

We will not attempt to insert a document with a different name but an email id that already exists in another document. Expectations are that the insertion operation will not work and through us an error of duplicate value. We have another document with a slightly different name: Sanket1, for the test purpose, and now we will attempt to update the document with an email: sanket@email.com.

Code:

db.educba.update( { “Name” : ”Sanket1” } , { $set : {email : “sanket@gmail.com” }})

Above query will aim to search a record with Name: Sanket1 and will update the record with adding an email id to the document, here $set will add a field for the document.

Output:

aim - MongoDB Unique

As you can see in the above screenshot, when we attempted to update a record with the different Name field, the email was the same as one existing document. It threw us a write error, which means an error occurred while writing the document. The error states “duplicate key error collection: test. educba index: email_1 dup key”. The error points to the issue and makes things clear for us to understand.  Like in our case, the email with the value of “sanket@email.com” is duplicated, already stored, so it will not store again due to unique indexing on the email field. In case you want to know, I’ve used the update with $get to add another field for existing records.

Use Case for this example: Is the New User Registration where we have to ensure that a single mail id is not used to create multiple accounts.

Conclusion

Implementing Unique Constraint will restrict the database from storing duplicate values for the same indexed key to wrap it up. This feature helps in storing documents with uniqueness. We learned and understood the syntax followed by the working of it. Then we implemented the unique constraint with example and understood the same along with screenshots, respectively.

Recommended Articles

This is a guide to MongoDB Unique. Here we discuss an introduction, how does Unique works and examples for better understanding. You can also go through our other related articles to learn more –

  1. MongoDB Collection
  2. Lookup in MongoDB
  3. Indexes in MongoDB
  4. MongoDB GUI Tools
  5. MongoDB insert | How to Work?
  6. MongoDB Update | How to Work?
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (14 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more