In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
创建索引可以指定一些选项,使用不同的选项建立的索引会有不同的行为。
一、唯一索引
唯一索引可以确保每一个文档的指定键都有唯一的值。例如,想确定文档中的username键不重复,创建一个唯一索引:
> db.users.findOne() { "_id" : ObjectId("54ad5826245d1b7d58b53238"), "i" : 2, "username" : "user2", "age" : 39, "created" : ISODate("2015-01-07T16:00:38.634Z") }> db.users.ensureIndex({"username":1},{"unique":true}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.users.insert({"username":"user2"}) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: blog.users.$username_1 dup key: { : \"user2\" }" } }) >
可以看出创建唯一索引后,就不能插入相同的键值;
1.唯一复合索引
创建唯一复合索引,复合索引的单键值可以重复,但是组成唯一复合索引的组合键值只能唯一。例如:
如果有一个{"username":"user2","age":18}有唯一的索引,下面的插入是合法的,
>db.users.insert({"username":"bob"})>db.users.insert({"username":"bob","age":23})>db.users.insert({"username":"fred","age":23})
如果再次插入这三项中的任意一个,会导致键重复异常;
2.去重复
对于已经有重复值的字段上创建唯一索引,会引起错误;可以使用dropDups选项遇到重复值会保留第一个,删除其他重复项;
>db.users.ensureIndex({"username":1},{"unique":true,"dropDups":true})
慎用这个选项,因为根本没有办法控制删除哪些文档;
二、稀疏索引
如果有一个可能存在也有可能不存在的字段,在此字段上创建的索引称为稀疏索引。
创建唯一稀疏索引:
>db.users.ensureIndex({"username":1},{"unique":true,"sparse":true})
创建非唯一稀疏索引:
>db.users.ensureIndex({"username":1},{"sparse":true})
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.