Unique Indexes
Parent: MongoDB Indexes Deep Dive · Published reference · snapshot 2026-10-24 · skill mongodb-cohort-ebff5b8ead9e
↓ Facts as markdownall context files
Source-anchored research for Unique Indexes. Run status: COMPLETED.
These notes link each claim to its source. Some citations identify archived research reports that are no longer hosted on this site. A published reference means the content is available; it does not certify independent review or accuracy.Read the editorial policy and follow the sources before relying on a claim.
How it works
- For ranged sharded collections, enforceable unique index patterns are the shard-key index or compound indexes prefixed by the full shard key. The default _id index is an exception to those pattern restrictions, but when _id is not the shard key it enforces uniqueness only within each shard. (low confidence) [source]
- A unique index enforces uniqueness of indexed keys across separate documents. Create one with db.collection.createIndex({ email: 1 }, { unique: true }); MongoDB also creates a unique _id index by default when creating a collection. (low confidence) [source]
How-to and procedures
- Create a unique index with createIndex({email:1},{unique:true}) to reject duplicate indexed values across documents; a compound unique index constrains the complete key combination. (low confidence) [source]
- To enforce both cross-document uniqueness and uniqueness of selected fields inside one document array, combine a unique multikey index with document schema validation. MongoDB demonstrates mapping the selected array fields to a set and comparing its size with the original array. (high confidence) [source]
Problems, failure modes and limitations
- In a non-sparse single-field unique index, both a missing field and an explicit null produce a null index entry. Only one document can occupy that entry; a second null or missing value causes a duplicate-key error. (high confidence) [source]
- A unique index build cannot successfully finish with conflicting keys. The index-build implementation temporarily tracks duplicate-key violations and rechecks them under a collection exclusive lock before committing; conflicts resolved during the build need not cause failure. (medium confidence) [source]
- Rolling procedures for building unique indexes on replica sets or sharded clusters require stopping collection writes. If writes cannot stop, the manual directs users to create the index on the replica-set primary or through mongos for the sharded collection. (low confidence) [source]
- Existing duplicate keys prevent a unique index build from succeeding. On a sharded collection, a build can succeed on shards without duplicates and fail on a shard containing duplicates, leaving inconsistent index definitions that require investigation. (high confidence) [source]
- During conversion, collMod cannot list conflicting document identifiers if its violations response exceeds 8MB. It instead reports too many conflicting documents; resolve duplicates and rerun the command to expose remaining conflicts. (low confidence) [source]
Comparisons and alternatives
- Mongoose's unique schema option requests a MongoDB unique index rather than a validation rule. A duplicate write raises a duplicate-key error rather than a Mongoose validation error, and writes can race index creation; await Model.init() when a test must wait for the index. (high confidence) [source]
- A compound unique index constrains the complete combination of indexed key values, rather than making every indexed field independently unique. A unique { tenantId: 1, email: 1 } index can therefore allow the same email in different tenants. (high confidence) [source]
- Mongoose schema option unique: true is a helper for building a MongoDB unique index, rather than a Mongoose validator. Violations surface as duplicate-key errors rather than Mongoose validation errors. (low confidence) [source]
Facts and statements
- A unique multikey index enforces uniqueness across documents, not within an array in one document. Repeated values inside one document can therefore survive; deduplicating an array requires an additional application or validation rule. (high confidence) [source]
- With unique:true and partialFilterExpression, uniqueness applies only to documents matching the filter. Documents outside the filter do not participate in that unique constraint. (low confidence) [source]
- The documented conversion workflow uses collMod with prepareUnique: true to reject new duplicate-key inserts, then unique: true with dryRun: true to identify existing conflicts. Resolve conflicts, repeat the dry run, and finalize with unique: true without dryRun. (medium confidence) [source]
- The historical SERVER-58936 regression allowed non-_id unique-index violations in MongoDB 4.4.7, 5.0.0 and 5.0.1. MongoDB's incident guidance dated August 17, 2021 identifies fixes in 4.4.8 and 5.0.2 and recommends checking for existing violations after upgrading. (low confidence) [source]
- MongoDB's SERVER-120790 report describes a rare collMod conversion race: another operation drops and recreates the index between validation and finalization, and descriptor-address reuse can make conversion accept an index containing duplicates. The reporter explicitly describes reproduction in practice as unlikely and mainly a testing concern. (low confidence) [source]
- MongoDB does not allow unique constraints on hashed indexes. (low confidence) [source]
- Combining unique: true with partialFilterExpression limits uniqueness enforcement to documents matching the filter. This supports optional identifiers by excluding documents without the indexed fields; an $exists: true filter still includes explicit null values. (high confidence) [source]
- In Mongoose, duplicate writes can succeed before the unique index has finished building. In tests that drop the database, await Model.init() before writing documents whose uniqueness depends on the rebuilt index. (low confidence) [source]
- Unique index guarantees on sharded collections require attention to collation as well as the shard-key prefix. SERVER-85346 documents how collated-equal strings routed to different shards can bypass per-shard unique indexes; the manual limits ensured sharded uniqueness to simple collation. (high confidence) [source]
- The May 14, 2026 update to SERVER-85346 lists fixes in 7.0.32, 8.0.21, 8.2.7 and 8.3.0 that reject incompatible unique-index, non-simple-collation sharding combinations. These safeguards do not automatically repair existing duplicate data; affected collections require duplicate detection and application-level cleanup. (low confidence) (verified as of 2026-05-14) [source]
Children
- Unique partial indexes (frontier)
- Unique multikey constraints and document validation (frontier)
- Converting existing indexes to unique (frontier)
- Sharded uniqueness and collation (frontier)
Frontier under this node: Converting existing indexes to unique, Sharded uniqueness and collation, Unique multikey constraints and document validation, Unique partial indexes