How to make a unique field in MongoDB?

To make a unique field in MongoDB, use unique: true when creating an index. This ensures that no duplicate values can be inserted into the specified field.

Syntax

db.collection.createIndex(
    { "fieldName": 1 },
    { unique: true }
);

Example

Let's create a unique index on the EmployeeName field ?

db.demo82.createIndex({"EmployeeName":1},{unique:true});
{
    "createdCollectionAutomatically" : true,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Insert Valid Documents

Insert documents with unique EmployeeName values ?

db.demo82.insertOne({"EmployeeName":"Chris"});
db.demo82.insertOne({"EmployeeName":"David"});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5e2bfb1b71bf0181ecc422a0")
}
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5e2bfb1f71bf0181ecc422a1")
}

Duplicate Value Error

Try inserting a duplicate EmployeeName ?

db.demo82.insertOne({"EmployeeName":"Chris"});
WriteError: E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : "Chris" }

Verify Result

Display all documents to confirm only unique values were inserted ?

db.demo82.find();
{ "_id" : ObjectId("5e2bfb1b71bf0181ecc422a0"), "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e2bfb1f71bf0181ecc422a1"), "EmployeeName" : "David" }

Conclusion

Creating a unique index prevents duplicate values from being inserted into a field. MongoDB throws an E11000 error when attempting to insert duplicate values, maintaining data integrity.

Updated on: 2026-03-15T01:51:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements