# MongoServerError: E11000 duplicate key error collection: test.users index: email_1 dup key: { email: null }

- **ID:** `mongodb/index-duplicate-key-on-sparse`
- **Domain:** mongodb
- **Category:** data_error
- **Error Code:** `11000`
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

Multiple documents have null or missing values for a field with a unique sparse index, causing a duplicate key error because sparse indexes treat null and missing values as the same key.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| mongodb-3.6 | active | — | — |
| mongodb-4.0 | active | — | — |
| mongodb-4.2 | active | — | — |
| mongodb-4.4 | active | — | — |
| mongodb-5.0 | active | — | — |
| mongodb-6.0 | active | — | — |
| mongodb-7.0 | active | — | — |

## Workarounds

1. **Use a partial unique index instead of sparse to allow multiple nulls. Example: `db.users.createIndex({email:1},{unique:true,partialFilterExpression:{email:{$exists:true,$ne:null}}})`** (95% success)
   ```
   Use a partial unique index instead of sparse to allow multiple nulls. Example: `db.users.createIndex({email:1},{unique:true,partialFilterExpression:{email:{$exists:true,$ne:null}}})`
   ```
2. **Update all documents with null email to a unique placeholder value, such as an empty string or a generated UUID. Example: `db.users.updateMany({email:null},{$set:{email:UUID().toString()}})`** (85% success)
   ```
   Update all documents with null email to a unique placeholder value, such as an empty string or a generated UUID. Example: `db.users.updateMany({email:null},{$set:{email:UUID().toString()}})`
   ```
3. **Drop the sparse index and create a regular unique index, ensuring that null values are replaced with a sentinel value first. Example: `db.users.dropIndex('email_1'); db.users.createIndex({email:1},{unique:true})`** (80% success)
   ```
   Drop the sparse index and create a regular unique index, ensuring that null values are replaced with a sentinel value first. Example: `db.users.dropIndex('email_1'); db.users.createIndex({email:1},{unique:true})`
   ```

## Dead Ends

- **** — This removes data integrity guarantees for non-null values, potentially allowing unintended duplicates. (15% fail)
- **** — This is a temporary fix; future inserts with null will cause the same error. (10% fail)
- **** — Existing null documents remain, so the error persists until they are also updated. (20% fail)
