6.唯一索引中的重複值處理
删除上述5中的索引,插入兩行一樣的記錄
coll.dropIndex("rsc");
檢視索引:
index ---------
{ "name" : "_id_" , "ns" : "ms_basic.schedule" , "key" : { "_id" : 1}}
如果現在直接在字段rsc上面建立唯一組合索引的時候肯定會報錯,我們來試一試:
{ "_id" : { "$oid" : "4c2fe764dd969674cb31a0be"} , "liveStatus" : 0 , "startDate" : "2010-11-12" , "isList" : 0 , "location" : "CAG" , "posttime" : "2010-04-01 15:04:57.0" , "rsc" : "WRM160513" , "noliveTvName" : "" , "endDate" : "2010-11-12" , "endTime" : "09:30" , "isGold" : 0 , "version" : 0 , "startTime" : "09:30" , "disciplineName" : "摔跤" , "event" : "160" , "gender" : "M" , "isMedal" : 0 , "discipline" : "WR" , "venueId" : "CAG" , "phaseName" : "資格賽" , "isRecommend" : 0 , "isData" : 0 , "eventUnitType" : "HATH" , "chatroomStatus" : 0 , "isChina" : 0 , "isStartTime" : 0 , "competitionStatus" : 0 , "unit" : "13" , "tvName" : "男子古典式 - 60公斤級資格賽" , "flag" : 0 , "scheduleName" : "資格賽" , "isEndTime" : 0 , "rid" : "" , "eventName" : "男子古典式 - 60公斤級" , "phase" : "5" , "isResult" : 0}
{ "_id" : { "$oid" : "4c3472bd2f0ba08b4e097918"} , "rsc" : "WRM160513" , "scheduleName" : "kaokao"}
再次建立索引:
coll.ensureIndex(new BasicDBObject("rsc", 1),"rsc",true);
顯示索引:
說明沒有建立成功,但是,居然不報錯??
看看指令行:報錯提示
> db.schedule.ensureIndex({rsc:1},{unique: true});
E11000 duplicate key error index: ms_basic.schedule.$rsc_1 dup key: { : "WRM160
513" }
檢視表schedule的索引,我們可以看到,新建立的索引沒有生成
> db.schedule.getIndexes();
[
{
"name" : "_id_",
"ns" : "ms_basic.schedule",
"key" : {
"_id" : 1
}
}
]
可以在第二個json對象加入一項dropDups: true,這樣在建立唯一組合索引的時候不會報錯,保留文檔中第一個重複的值,其它重複的值均删除。
再次測試一下,加入dropDups選項,雖然報錯了,但是唯一組合索引已經建立了。
> db.schedule.ensureIndex({rsc:1},{unique:true,dropDups:true});
成功!再次查詢表中的記錄,發現重複的記錄已經自動删除了。
再次插入試試:
java中插入,居然還是不報錯,順利通過,可惜沒有入庫,看看指令行吧:
> db.schedule.insert({rsc: 'WRM160513', scheduleName: 'kaokao'});
MongoDB官方文檔的說明
A unique index cannot be created on a key that has duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate values, add the dropDups option.
db.schedule.ensureIndex({rsc:1},{unique:true,dropDups:true})
本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/365915