第27章:MongoDB-索引--唯一索引

①唯一索引

唯一索引的目的是为了让数据库的某个字段的值唯一,为了确保数据的都是合法的,但是唯一索引在插入数据时会对数据进行检查,一旦重复会抛出异常,效率会比较低,唯一索引只是保证数据库数据唯一的最后一种手段,而不是最佳方式,更不是唯一方式,为了保证效率最好采用别的解决方案来保证数据的唯一合法性,尽量减少数据库的压力。

②唯一索引
> db.foo.ensureIndex({"username": 1}, {"unique": true})
{
        "createdCollectionAutomatically" : true,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.foo.insert({"username": "mengday", "email": "[email protected]", "age": 26})
WriteResult({ "nInserted" : 1 })
// username 重复会报错
> db.foo.insert({"username": "mengday", "email": "[email protected]"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: test.foo index: username_1 dup key: { : \"mengday\" }"
        }
})
 
// 第一次 插入不包含索引键的文档,插入成功,不包含索引键系统会默认为索引键的值为null
> db.foo.insert({"email": "[email protected]"})
WriteResult({ "nInserted" : 1 })
 
// 第二次插入不包含唯一索引的键,插入失败,因为不包含键,键的值就null,第一次已经有一个值为null, 再插入null,就是重复
> db.foo.insert({"email": "[email protected]"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: test.foo index: username_1 dup key: { : null }"
        }
})
 
// 对多个字段创建唯一索引(关系数据库中的联合主键)
db.user.ensureIndex({"username": 1, "nickname": 1}, {"unique": true})
>
③稀疏索引
稀疏索引:对不存在的键就不进行索引,也就是该文档上没有建立索引,索引条目中也不包含 索引键为null的索引条目,所以再次插入不包含索引键的文档不会报错,直接插入。注意:稀疏索引不光和唯一索引配合使用,也可以单独使用
 
> 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": "[email protected]"})
WriteResult({ "nInserted" : 1 })
> db.foo.insert({"email": "[email protected]"})
WriteResult({ "nInserted" : 1 })
> db.foo.insert({"username": "mengday3", "email": "[email protected]"})
WriteResult({ "nInserted" : 1 })
> db.foo.insert({"username": "mengday3", "email": "[email protected]"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: test.foo index: username_1 dup key: { : \"mengday3\" }"
        }
})
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/Lucky-stars/p/10555374.html