一、索引的CRUD
创建索引:ensureIndex()
db.collection.ensureIndex({"name":1}) 为collection的name属性创建正序索引
db.collection.ensureIndex({"name":1},{unique:true}) 为collection的name属性创建正序唯一索引。
db.collection.ensureIndex({"name":1},{unique:true,dropDups:true}) 为collection的name属性创建正序唯一索引。剔除为唯一重复值(在建唯一索引前已经存在重复值)。
查看索引:getIndexes()
db.system.indexes.find() 查看当前数据库的所有索引。 所有数据库都存在索引文档system.indexes
db.system.namespaces.find() 查看当前数据库的所有索引。
db.collection.getIndexes() 查询当前数据库中指定collection的索引。
删除索引:dropIndex()
db.collection.dropIndex({"name":1}) 删除collection中的name属性的索引。
db.collection.dropIndex("name_1") 删除collection中索引名称为name_1的索引
db.runCommand({dropIndexes:"collection",index:"indexName"}) 删除当前数据库中collection文档的索引名称为indexName的索引。注意indexName是索引名称,不是文档的属性名称。
db.runCommand({dropIndexes:"collection",index:"*"}) 删除当前数据库中collection文档的所有索引。
查询时指定索引:
Hint
eg:db.user.find({name:'张三',sex:'男'}).hint({name:1}); #指定索引key
db.user.find({name:'张三',sex:'男'}).hint("name_1"); #指定索引名称
注意:查询时指定索引时指定索引必须存在。
db.collection.getIndexes(); 查询指定集合的索引列表
重建索引 reindex()
语法:db.collection.reIndex()
适用场景:一个表经过大量的修改后会导致表的文件上产生空洞,索引文件也是一样,
可以通过重建索引来提高索引的效率。
不好的地方:对于数据量大或者索引多的表来说,重建索引代价重大。
一般不需要重建索引,只有集合大小发生显巨变化或磁盘空间占用不成比例时才需要
二、索引的分类
1、默认索引
2、单列索引
3、组合索引
db.collection.ensureIndex({"provinceId":1,"isDied":1});
注意:组合索引支持的索引查询只是索引的任意前缀索引字段。
eg:
建表:
db.products.insert({
"_id": ObjectId("56c448bb4b3a77a13d33d5d6"),
"item": "Banana",
"category": ["food", "produce", "grocery"],
"