我正在嘗試學習Mongodb中的索引。我創建了一個數據庫,並收集如下:Mongodb-在現有集合上添加唯一索引
use mydb
db.createCollection("myFirstCollection")
one={name:"Helios"}
two={name:"Kepler"}
db.myFirstCollection.insert(one)
db.myFirstCollection.insert(two)
我能列出我的結果如下:
db.myFirstCollection.find()
{ "_id" : ObjectId("53cde256f8807057b6bd827b"), "name" : "Helios" }
{ "_id" : ObjectId("53cde25bf8807057b6bd827c"), "name" : "kepler" }
我想在球場上name
添加唯一索引。但是當我嘗試時,得到以下錯誤
db.myFirstCollection.ensureIndex({name:1},{unique:true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"ok" : 0,
"errmsg" : "E11000 duplicate key error index: mydb.myFirstCollection.$name_1 dup key: { : null }",
"code" : 11000
}
我無法弄清楚我所做的錯誤。請幫忙。
什麼是db.myFirstCollectio.getIndexes()顯示? – Wilbeibi
當我在shell中嘗試你的代碼時,它工作正常。該錯誤消息意味着'myFirstCollection'中還有其他文檔沒有'name'字段。 – JohnnyHK
嘗試將'sparse'指定爲'true',這樣如果文檔沒有該字段,它們將不會包含在索引中。即:'db.myFirstCollection.ensureIndex({name:1},{unique:true,sparse:true})' – ujvl