MongoDB索引

1、查看索引
  查看数据库使用到的所有索引
  db.system.indexes.find()
  db.system.spacename.find()

  查看指定文档使用的索引
  db.collection.getIndexes();

2、创建索引
  创建普通的单列索引
  db.collection.ensureIndex({field:1/-1}); 1是升续 2是降续
  为集合persons中的age字段添加索引
  db.persons.ensureIndex({age:1}); //正序索引
  db.persons.ensureIndex({age:-1}); //倒序索引

  创建多列索引
  db.collection.ensureIndex({field1:1/-1, field2:1/-1}); //以field1和field2的值作为索引,区别于分别以field1和field2建立索引

  创建子文档索引
  db.collection.ensureIndex({filed.subfield:1/-1});

  创建索引时指定索引名称
  db.persons.ensureIndex({age:1},{name:'agesort'}); //以age字段建立索引,索引名为agesort

  建立唯一索引
  db.collection.ensureIndex({filed:1/-1}, {unique:true});
  db.persons.ensureIndex({name:1},{unique:true})

  如果要使用某个字段建立唯一索引,但是该字段在集合中已经存在重复值,则针对该字段
  建立唯一索引会失败,但是可以剔除重复值建立唯一索引
  db.persons.ensureIndex({name:1},{unique:true,dropDups:true})
  这样以name字段建立唯一索引,如果出现重复值就以留下第一个,剔除其余重复值对应的文档记录

  创建稀疏索引:
  稀疏索引的特点------如果针对field做索引,针对不含field列的文档,将不建立索引.
  与之相对,普通索引,会把该文档的field列的值认为NULL,并建索引.
  适宜于: 小部分文档含有某列时.
  db.collection.ensureIndex({field:1/-1},{sparse:true});

  创建哈希索引(2.4新增的)
  哈希索引速度比普通索引快,但是,无能对范围查询进行优化.
  适宜于---随机性强的散列
  db.collection.ensureIndex({file:’hashed’});

3、删除索引

   删除单个索引

  db.collection.dropIndex({filed:1/-1});

  

  删除文档所有索引

  db.collection.dropIndexes();

  db.runCommand({dropIndexes:'persons',index:'name'}) //删除persons集合中名称为name的索引
  db.runCommand({dropIndexes:'persons',index:'*'}) //删除person集合中所有索引

4、重建索引
  db.collection.reIndex() 可减少索引文件碎片

  查询时强制使用指定索引(该索引必须已经被建立,存在)
  db.persons.find({age:25}).hint({name:1}) 查询年龄为25岁的人,并使用索引name


5、查看当前查询语句的具体信息
  db.persons.find({name:"zhangsan"}).explain()
  可以看到该查询语句使用到了那些索引,消耗时间等信息


  由于创建索引时,系统会暂时锁表,为了不影响增删改查的性能,可以让创建索引的过程在后台执行
  db.persons.ensureIndex({name:1},{background:true})

原文地址:https://www.cnblogs.com/iaknehc/p/6682481.html