How to restrict inserting an item with the same name in MongoDB?

To restrict inserting items with the same name in MongoDB, create a unique index on the field using createIndex() with unique: true. This prevents duplicate values and throws an error when attempting to insert duplicates.

Syntax

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

Example

Create a unique index on the SubjectName field to prevent duplicate subject names ?

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

Insert Unique Documents

db.demo316.insertOne({"SubjectName": "MySQL"});
db.demo316.insertOne({"SubjectName": "MongoDB"});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e50e378f8647eb59e56205d")
}
{
    "acknowledged": true,
    "insertedId": ObjectId("5e50e37df8647eb59e56205e")
}

Attempt Duplicate Insert

Trying to insert a duplicate "MongoDB" will throw an error ?

db.demo316.insertOne({"SubjectName": "MongoDB"});
WriteError: E11000 duplicate key error collection: test.demo316 index: SubjectName_1 dup key: { : "MongoDB" }

Verify Documents

db.demo316.find();
{"_id": ObjectId("5e50e378f8647eb59e56205d"), "SubjectName": "MySQL"}
{"_id": ObjectId("5e50e37df8647eb59e56205e"), "SubjectName": "MongoDB"}

Key Points

  • Use createIndex() instead of the deprecated ensureIndex() method.
  • The unique constraint applies only to the indexed field values.
  • Error code E11000 indicates a duplicate key violation.

Conclusion

Creating a unique index with createIndex({"field": 1}, {unique: true}) effectively prevents duplicate values in MongoDB collections. The database automatically rejects any insert operation that would create a duplicate key.

Updated on: 2026-03-15T02:28:50+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements