MongoDb索引

Mongo 索引

语法:db.collection.ensureIndex({filed:1});

注:1.默认是曾序索引

        2.默认索引是用btree组织

说明:1代表asc升序索引 -1 降序

子文档创建索引:

db.collection.ensureIndex({'fleld.subfiled':1});

说明: 为collection中文档的filed域下的subfiled域建索引

例: db.user.insert({userid:1,email:'aa@a.com',intro:{height:175,age:24}}

      db.user.ensoueIndex({'intro.height':1,'intro.age':1});

说明:此例为user表下的intro字段中的height,age字段建索引

多列创建索引:

db.collection.ensureIndex({field:1/-1},{unique:true});

说明: 1:field列上设置唯一索引 2:也可以针对"多列"设置唯一索引

例: db.user.ensureIndex({userid:1},{unique:true});

     db.user.ensureIndex({a:1,b:1},{unique:true});

稀疏索引创建

db.collection.ensureIndex({field:1/-1},{sparse:true});

说明:稀疏索引是指--只针对含有field列的document建索引 而不指定此项,则不含field列的文档,把field的值理解为null,再建索引

例: db.user.ensureIndex({school:1},{sparse:true});

      db.user.find({school:null});

哈希索引创建

 db.collection.ensureIndex({field:'hashed'});

说明: 1. 可以单个字段或子文本字段上建立hash索引

         2. 不可以针对"多个列"建立hash索引 例: db.collection.ensureIndex('intro.height':'hashed');

查看已有索引

db.collection.getIndexes();

删除指定索引:

db.collections.dropIndex({filed:1/-1/'hashed'});

例: db.user.dropIndex({'intro.height':'hashed'});

删除所有索引:

db.collection.dropIndexes();

注:_id列的索引不会被删除

重建索引

db.collection.reIndex()

作用: 重建collection中的所有索引,包括_id 意义: 减少索引文件碎片

例: db.user.reIndex()

posted @   ni当像鸟飞往你的山  阅读(123)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示