# MongoServerError: Index build failed: E11000 duplicate key error collection: db.users index: email_1 dup key

**Code:** `createIndex failed: unique index with duplicates` · **Category:** MongoDB · **Seen on:** MongoDB

You tried to build a unique index but existing documents already contain duplicate values.

## Meaning

Find the duplicates with an aggregation (`$group` by field, `$match` count > 1), merge or delete them, then rebuild. For optional fields use a partial index. Building on production: do it in a maintenance window or use `createIndex` with care since index builds take time/resources.

## Common causes

- Duplicate values already in the collection
- Many documents missing the field (null collisions)
- Case differences treated as distinct
- Previous partial failed build
- Data imported without constraints

## Quick fix

1. Find duplicates: `db.users.aggregate([{ $group: { _id: "$email", n: { $sum: 1 }, ids: { $push: "$_id" } } }, { $match: { n: { $gt: 1 } } }])`
2. Clean the data, then retry `createIndex`
3. Use `partialFilterExpression` for optional fields

## Detailed fix by platform

### mongosh

1. `db.users.createIndex({ email: 1 }, { unique: true, partialFilterExpression: { email: { $type: "string" } } })`

## How to diagnose

1. **Duplicates** — Which values?
2. **Nulls** — Missing field?
3. **Window** — Production load?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/mongodb/createindex-duplicate-key-existing-data)
