Avoid duplicate entries in MongoDB?

To avoid duplicate entries in MongoDB, create a unique index on the field that should have unique values. This prevents insertion of documents with duplicate values and throws an error if attempted.

Syntax

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

Example: Create Unique Index

Let's create a unique index on the UserName field to prevent duplicate usernames ?

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

Test with Valid Insert

Insert the first record with username "John" ?

db.avoidDuplicateEntriesDemo.insertOne({"UserName": "John"});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c90e1824afe5c1d2279d697")
}

Test Duplicate Prevention

Attempt to insert a duplicate username "John" ?

db.avoidDuplicateEntriesDemo.insertOne({"UserName": "John"});
WriteError: E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : "John" }

Insert Different Value

Insert a record with a different username "Carol" ?

db.avoidDuplicateEntriesDemo.insertOne({"UserName": "Carol"});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c90e18d4afe5c1d2279d699")
}

Verify Results

db.avoidDuplicateEntriesDemo.find();
{ "_id": ObjectId("5c90e1824afe5c1d2279d697"), "UserName": "John" }
{ "_id": ObjectId("5c90e18d4afe5c1d2279d699"), "UserName": "Carol" }

Key Points

  • The unique: true option enforces uniqueness at the database level
  • MongoDB throws error code E11000 when duplicate insertion is attempted
  • Create unique indexes before inserting data to avoid conflicts with existing duplicates

Conclusion

Unique indexes provide an effective way to prevent duplicate entries in MongoDB. The database automatically rejects any insert or update operation that would create duplicate values in the indexed field.

Updated on: 2026-03-15T00:17:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements