Skip to content

Indexing

Unique Indexes

Enforce uniqueness in the database, not only in application code.

IntermediateAbout 3 minutes

A unique index is a constraint. Two documents cannot share the same key. _id already is one. email on users should be another — a race between two signups is a duplicate key error, not a 'check in Node then insert'.

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

db.cartItems.createIndex({ userId: 1, sku: 1 }, { unique: true })
One email. Compound unique — one SKU per cart, not globally.

Missing and null count as a value. Two documents with no `email` violate { email: 1 } unique. Old fix: sparse: true (index only docs that have the field). Better: partialFilterExpression: { email: { $type: "string" } } so only real emails are unique. Unique does not make a bad email format valid — that is schema validation.

Interview question

How do you enforce a unique email in MongoDB?

Think about it first.