问题:原有的索引没有 unique
唯一属性,为其添加 unique
。
一、查询索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| mgset-44912522:PRIMARY> db.user.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.user" }, { "v" : 2, "key" : { "username" : 1 }, "name" : "username", "ns" : "mydb.user" } ]
|
接下来,给username索引增加唯一属性,要先删除旧索引,再重新建立新的索引。
二、删除索引
1 2 3 4 5 6 7 8 9 10 11 12 13
| mgset-44912522:PRIMARY> db.user.dropIndex('username') { "nIndexesWas" : 3, "ok" : 1, "$clusterTime" : { "clusterTime" : Timestamp(1713167379, 1), "signature" : { "hash" : BinData(0,"sRHeElmSwQZdxoUt6OU0PIZhnOc="), "keyId" : NumberLong("7316702510742241281") } }, "operationTime" : Timestamp(1713167379, 1) }
|
三、重建索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| mgset-44912522:PRIMARY> db.user.createIndex({ username: 1 }, { unique: true })
# 这个错误是由于数据中已经存在多个数据 { username: \"helloworld\" },删除多余的保留一个即可。 { "operationTime" : Timestamp(1713167425, 1), "ok" : 0, "errmsg" : "E11000 duplicate key error collection: mydb.user index: username_1 dup key: { username: \"helloworld\" }", "code" : 11000, "codeName" : "DuplicateKey", "keyPattern" : { "username" : 1 }, "keyValue" : { "username" : "helloworld" }, "$clusterTime" : { "clusterTime" : Timestamp(1713167425, 1), "signature" : { "hash" : BinData(0,"Tbzv65r2RnDFtVf1NSsZHD+ptTU="), "keyId" : NumberLong("7316702510742241281") } } }
|
数据删除之后,重新执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| mgset-44912522:PRIMARY> db.user.createIndex({ username: 1 }, { unique: true }) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1, "$clusterTime" : { "clusterTime" : Timestamp(1713167572, 2), "signature" : { "hash" : BinData(0,"7baxP78Ao5NVroY+BdehOEhyrE4="), "keyId" : NumberLong("7316702510742241281") } }, "operationTime" : Timestamp(1713167572, 2) }
|
四、再次查询索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| mgset-44912522:PRIMARY> db.user.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.user" }, { "v" : 2, "unique" : true, "key" : { "username" : 1 }, "name" : "username_1", "ns" : "mydb.user" } ]
|