Index Properties: Unique, Sparse, Partial, TTL
Learners will create specialised indexes with unique, sparse, partial, and TTL properties to enforce constraints and automate cleanup.
Index Properties Overview
Beyond the basic B-tree structure, MongoDB indexes support several property modifiers that change how they behave: unique enforces distinctness, sparse skips null entries, partial limits the index to a subset of documents, and TTL automatically expires documents. Each property is set in the options object of createIndex() and serves a specific purpose in production schemas.
Unique Indexes
A unique index guarantees that no two documents in the collection can have the same value for the indexed field. Any insert or update that would produce a duplicate triggers a DuplicateKey error. Unique indexes are commonly used on fields like email, username, or any natural key. The _id index is always unique.
// Unique index on email
db.users.createIndex(
{ email: 1 },
{ unique: true }
);
// First insert succeeds
db.users.insertOne({ email: 'alice@example.com', name: 'Alice' });
// Second insert with same email throws E11000 DuplicateKey
db.users.insertOne({ email: 'alice@example.com', name: 'Bob' });All lessons in this course
- How MongoDB B-Tree Indexes Work
- Creating Single-Field and Compound Indexes
- Index Properties: Unique, Sparse, Partial, TTL
- Reading explain() Output to Diagnose Queries