mongoDB ユニークなindexを作成する

mongoDB ユニークなindexを作成する

mongoDBで、ユニークなindexを作成する手順を記述してます。既にユニークになっていないコレクションに対しては作成できません。

環境

  • OS CentOS Stream release 9
  • MongoDB 6.0.2

手順

ユニークなindexを作成するには、「createIndex」で「unique:true」を使用します。

db.コレクション名.createIndex({フィールド名:1},{unique:true, name:"インデックス名"})

実際に、以下のデータベース「hoge」にある「foo」というコレクションに設定してみます。

> db.foo.find()
[
  {
    _id: ObjectId("639ab5816dcdc72cf1d5b3ca"),
    name: 'itiro',
    age: 10,
    gender: 'm'
  }
]

設定してみます。

> db.foo.createIndex({name:1},{unique:true, name:"u1"})

u1

ユニークになったフィールドには、重複するデータはinsertできません。

> db.foo.insertOne({name:'itiro', age:20, gender:'m'})
MongoServerError: E11000 duplicate key error collection: hoge.foo index: u1 dup key: { name: "itiro" }

また、既に存在するデータに対して、ユニークになっていないフィールドに対してユニークなindexを付与しようとすると以下のエラーが発生します。

MongoServerError: Index build failed: dadeedc8-da83-4a3e-8155-9835a362f3de: Collection hoge.foo ( 517baef1-4633-44df-b8ef-0bb50ad8a748 ) :: caused by :: E11000 duplicate key error collection: hoge.foo index: u1 dup key: { name: "jiro" }