Unique, partial and sparse indexes

Enforce unique values or index only part of the collection.

Enforce unique values across the cluster or index only the documents you care about.

Requirements

  • A user with dbAdmin or readWrite on the database.

Unique

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

It is unique across the cluster, also in a collection with a shard key.

Partial

JavaScript
db.orders.createIndex({ created: 1 }, { partialFilterExpression: { status: "pending" } });

Sparse

JavaScript
db.users.createIndex({ phone: 1 }, { sparse: true });

Check

An insert with an email that already exists in the collection fails with DuplicateKey (11000) and is not stored.

Common problems

  • The unique index is not created because the collection already has repeated values in that field.

See also