唯一索引的主要目的是用在某一个字段上,使该字段的内容不重复。
范例:创建一个唯一索引
> db.emp.createIndex({"name":1},{"unique":true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
在name字段上的内容不允许重复。
范例:在emp集合中增加name重复的数据
> db.emp.insert({"name":"王八","sex":"男","age":35,"sal":8000,"loc":"北京"});
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: hr.emp index: name_1 dup key: { : \"王八\" }"
}
})
由于在name字段上设置了唯一索引,所以出现了以上错误信息。
范例:创建一个唯一索引
> db.emp.createIndex({"name":1},{"unique":true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
在name字段上的内容不允许重复。
范例:在emp集合中增加name重复的数据
> db.emp.insert({"name":"王八","sex":"男","age":35,"sal":8000,"loc":"北京"});
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: hr.emp index: name_1 dup key: { : \"王八\" }"
}
})
由于在name字段上设置了唯一索引,所以出现了以上错误信息。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28536251/viewspace-2144102/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/28536251/viewspace-2144102/