MeWrite Docs

E11000 duplicate key error

MongoDBで一意インデックスに違反するドキュメントを挿入した場合に発生

概要

E11000 duplicate key errorは、MongoDBで一意インデックス(unique index)が設定されたフィールドに重複する値を挿入しようとした場合に発生します。

エラーメッセージ

E11000 duplicate key error collection: mydb.users index: email_1 dup key: { email: "john@example.com" }

原因

  1. 重複データの挿入: 既に存在する値を挿入
  2. _idの重複: 同じ_idを持つドキュメントを挿入
  3. 一意インデックスの後付け: 既存データに重複がある状態でインデックス作成

解決策

1. upsertを使用

1
2
3
4
5
db.users.updateOne(
  { email: "john@example.com" },
  { $set: { name: "John" } },
  { upsert: true }
)

2. insertManyでordered: falseを使用

1
2
3
4
5
6
7
db.users.insertMany(
  [
    { email: "john@example.com", name: "John" },
    { email: "jane@example.com", name: "Jane" }
  ],
  { ordered: false }  // エラーが発生しても続行
)

3. bulkWriteでエラーハンドリング

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try {
  db.users.bulkWrite([
    { insertOne: { document: { email: "john@example.com" } } }
  ])
} catch (e) {
  if (e.code === 11000) {
    console.log("Duplicate key, updating instead");
    // 更新処理
  }
}

4. findOneAndUpdateで安全に処理

1
2
3
4
5
6
7
8
db.users.findOneAndUpdate(
  { email: "john@example.com" },
  {
    $setOnInsert: { createdAt: new Date() },
    $set: { name: "John", updatedAt: new Date() }
  },
  { upsert: true, returnDocument: "after" }
)

5. 既存の重複を確認してからインデックス作成

1
2
3
4
5
6
7
8
// 重複確認
db.users.aggregate([
  { $group: { _id: "$email", count: { $sum: 1 } } },
  { $match: { count: { $gt: 1 } } }
])

// 重複解消後にインデックス作成
db.users.createIndex({ email: 1 }, { unique: true })

MongoDB の他のエラー

最終更新: 2025-12-09