第27章:MongoDB-索引--唯一索引
生活随笔
收集整理的這篇文章主要介紹了
第27章:MongoDB-索引--唯一索引
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
①唯一索引
唯一索引的目的是為了讓數(shù)據(jù)庫(kù)的某個(gè)字段的值唯一,為了確保數(shù)據(jù)的都是合法的,但是唯一索引在插入數(shù)據(jù)時(shí)會(huì)對(duì)數(shù)據(jù)進(jìn)行檢查,一旦重復(fù)會(huì)拋出異常,效率會(huì)比較低,唯一索引只是保證數(shù)據(jù)庫(kù)數(shù)據(jù)唯一的最后一種手段,而不是最佳方式,更不是唯一方式,為了保證效率最好采用別的解決方案來保證數(shù)據(jù)的唯一合法性,盡量減少數(shù)據(jù)庫(kù)的壓力。
②唯一索引 > db.foo.ensureIndex({"username": 1}, {"unique": true}) { ? ? ? ? "createdCollectionAutomatically" : true, ? ? ? ? "numIndexesBefore" : 1, ? ? ? ? "numIndexesAfter" : 2, ? ? ? ? "ok" : 1 } > db.foo.insert({"username": "mengday", "email": "mengday@163.com", "age": 26}) WriteResult({ "nInserted" : 1 }) // username 重復(fù)會(huì)報(bào)錯(cuò) > db.foo.insert({"username": "mengday", "email": "mengday2@163.com"}) WriteResult({ ? ? ? ? "nInserted" : 0, ? ? ? ? "writeError" : { ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: test.foo index: username_1 dup key: { : \"mengday\" }" ? ? ? ? } }) ? // 第一次 插入不包含索引鍵的文檔,插入成功,不包含索引鍵系統(tǒng)會(huì)默認(rèn)為索引鍵的值為null > db.foo.insert({"email": "mengday3@163.com"}) WriteResult({ "nInserted" : 1 }) ? // 第二次插入不包含唯一索引的鍵,插入失敗,因?yàn)椴话I,鍵的值就null,第一次已經(jīng)有一個(gè)值為null, 再插入null,就是重復(fù) > db.foo.insert({"email": "mengday4@163.com"}) WriteResult({ ? ? ? ? "nInserted" : 0, ? ? ? ? "writeError" : { ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: test.foo index: username_1 dup key: { : null }" ? ? ? ? } }) ? // 對(duì)多個(gè)字段創(chuàng)建唯一索引(關(guān)系數(shù)據(jù)庫(kù)中的聯(lián)合主鍵) db.user.ensureIndex({"username": 1, "nickname": 1}, {"unique": true}) > ③稀疏索引 稀疏索引:對(duì)不存在的鍵就不進(jìn)行索引,也就是該文檔上沒有建立索引,索引條目中也不包含 索引鍵為null的索引條目,所以再次插入不包含索引鍵的文檔不會(huì)報(bào)錯(cuò),直接插入。注意:稀疏索引不光和唯一索引配合使用,也可以單獨(dú)使用 ? > db.foo.drop() true > db.foo.ensureIndex({"username": 1}, {"unique": true, "sparse": true}) { ? ? ? ? "createdCollectionAutomatically" : true, ? ? ? ? "numIndexesBefore" : 1, ? ? ? ? "numIndexesAfter" : 2, ? ? ? ? "ok" : 1 } > db.foo.insert({"email": "mengday1@163.com"}) WriteResult({ "nInserted" : 1 }) > db.foo.insert({"email": "mengday2@163.com"}) WriteResult({ "nInserted" : 1 }) > db.foo.insert({"username": "mengday3", "email": "mengday3@163.com"}) WriteResult({ "nInserted" : 1 }) > db.foo.insert({"username": "mengday3", "email": "mengday3@163.com"}) WriteResult({ ? ? ? ? "nInserted" : 0, ? ? ? ? "writeError" : { ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: test.foo index: username_1 dup key: { : \"mengday3\" }" ? ? ? ? } }) ④?
⑤?
⑥?
⑦?
⑧?
⑨?
⑩?
??
??
??
??
??
??
??
??
??
??
轉(zhuǎn)載于:https://www.cnblogs.com/Lucky-stars/p/10555374.html
總結(jié)
以上是生活随笔為你收集整理的第27章:MongoDB-索引--唯一索引的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试题:如何编写一个杯子测试用例
- 下一篇: 201671010423 词频统计软件