How to keep two "columns" in MongoDB unique?

To keep two fields unique together in MongoDB, create a compound unique index on both fields. This ensures that the combination of both field values must be unique across the collection.

Syntax

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

Example: Create Compound Unique Index

Create a unique index on StudentFirstName and StudentLastName fields ?

db.keepTwoColumnsUniqueDemo.createIndex(
    {"StudentFirstName": 1, "StudentLastName": 1},
    {unique: true}
);
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Insert Valid Documents

Insert documents with unique combinations of first and last names ?

db.keepTwoColumnsUniqueDemo.insertMany([
    {"StudentFirstName": "John", "StudentLastName": "Smith", "StudentAge": 21},
    {"StudentFirstName": "John", "StudentLastName": "Doe", "StudentAge": 23}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd30fd7b64f4b851c3a13e5"),
        ObjectId("5cd30fe5b64f4b851c3a13e6")
    ]
}

Duplicate Insert Attempt

Attempt to insert a duplicate combination of John Smith ?

db.keepTwoColumnsUniqueDemo.insertOne(
    {"StudentFirstName": "John", "StudentLastName": "Smith", "StudentAge": 24}
);
WriteError: E11000 duplicate key error collection: sample.keepTwoColumnsUniqueDemo 
index: StudentFirstName_1_StudentLastName_1 dup key: { : "John", : "Smith" }

Verify Documents

Display all documents in the collection ?

db.keepTwoColumnsUniqueDemo.find().pretty();
{
    "_id": ObjectId("5cd30fd7b64f4b851c3a13e5"),
    "StudentFirstName": "John",
    "StudentLastName": "Smith",
    "StudentAge": 21
}
{
    "_id": ObjectId("5cd30fe5b64f4b851c3a13e6"),
    "StudentFirstName": "John",
    "StudentLastName": "Doe",
    "StudentAge": 23
}

Key Points

  • The compound unique index prevents duplicate combinations of the specified fields
  • Individual field values can repeat as long as the combination is unique
  • MongoDB returns an E11000 duplicate key error when attempting to insert duplicates

Conclusion

Compound unique indexes in MongoDB enforce uniqueness across multiple fields together. Use createIndex() with the unique: true option to prevent duplicate combinations while allowing individual field repetition.

Updated on: 2026-03-15T01:06:33+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements