您好,登錄后才能下訂單哦!
Part1:寫在最前
MongoDB的 unique index索引這里有個注意事項,主要體現在對NULL值的處理上,本文加以復現。
整體環境:
MongoDB 3.2.5
Part2:集合內容
PRIMARY> db.helei.find() { "_id" : ObjectId("58b7ea9544e98b24a5bdcef5"), "i" : 0, "username" : "user0", "age" : 8, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcef6"), "i" : 1, "username" : "user1", "age" : 9, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcef7"), "i" : 2, "username" : "user2", "age" : 82, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcef8"), "i" : 3, "username" : "user3", "age" : 48, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcef9"), "i" : 4, "username" : "user4", "age" : 27, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcefa"), "i" : 5, "username" : "user5", "age" : 53, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcefb"), "i" : 6, "username" : "user6", "age" : 42, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcefc"), "i" : 7, "username" : "user7", "age" : 56, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcefd"), "i" : 8, "username" : "user8", "age" : 5, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b7ea9544e98b24a5bdcefe"), "i" : 9, "username" : "user9", "age" : 56, "created" : "Thu Mar 02 2017 17:49:09 GMT+0800 (CST)" } { "_id" : ObjectId("58b8da80d8509e8f46fd9042"), "i" : "10", "age" : 50, "create" : ISODate("2017-03-03T02:52:48.834Z") }
這里可以看到,我在helei集合中生成了i從0到10這些數據,而i:10文檔中我故意漏寫username這一個鍵值
Part3:集合索引情況
PRIMARY> db.helei.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "helei.helei" }, { "v" : 1, "key" : { "age" : 1 }, "name" : "idx_age", "ns" : "helei.helei" }, { "v" : 1, "unique" : true, "key" : { "username" : 1 }, "name" : "uk_username", "ns" : "helei.helei", "background" : true } ]
這里可以看出在name列添加了unique index: uk_username
Part4:驗證
當再有一個不包含username鍵值的文檔被插入時,會拋出錯誤
PRIMARY> db.helei.insert({i:"11",age:51,create:new Date()})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: helei.helei index: uk_username dup key: { : null }"
}
})
Warning:警告
如果一個文檔沒有對應的鍵,索引會將其作為null存儲。
——總結——
如果對某個鍵建立了唯一索引,但插入了多個缺少該索引鍵的文檔,由于集合已經存在一個該索引鍵值的值為null而導致插入失敗。由于筆者的水平有限,編寫時間也很倉促,文中難免會出現一些錯誤或者不準確的地方,不妥之處懇請讀者批評指正。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。