一 . 索引概述和基本操作

1. 索引提高查询速度,降低写入速度,权衡常用的查询字段,不必在太多列上建索引
2. 在mongodb中,索引可以按字段升序/降序来创建,便于排序
3. 默认是用btree来组织索引文件,2.4版本以后,也允许建立hash索引.

常用命令:
查看当前索引状态: db.collection.getIndexes();

创建普通的单列索引:db.collection.ensureIndex({field:1/-1}); 1是升续 2是降续

删除单个索引
db.collection.dropIndex({filed:1/-1});

一下删除所有索引
db.collection.dropIndexes();

创建多列索引 db.collection.ensureIndex({field1:1/-1, field2:1/-1});

例子:

 > for (var i = ;i<=;i++){
... db.stu.insert({sn:i,name:'student'+i})
... };
>
>
> db.stu.find().count(); > db.stu.find({sn:});
{ "_id" : ObjectId("574271a9addef29711337c28"), "sn" : , "name" : "student99" }
> db.stu.find({sn:}).explain();
{
"cursor" : "BasicCursor", -- 无索引相当于mysql的全表扫描
"isMultiKey" : false,
"n" : ,
"nscannedObjects" : , -- 扫描了1000行
.... > db.stu.ensureIndex({sn:}); --创建索引
> db.stu.find({sn:}).explain();
{
"cursor" : "BtreeCursor sn_1", --使用了索引
"isMultiKey" : false,
"n" : ,
"nscannedObjects" : , --只用扫描一行
...
} > db.stu.getIndexes(); --查询索引
[
{
"v" : ,
"key" : {
"_id" : -- 默认创建 正序
},
"ns" : "test.stu",
"name" : "_id_"
},
{
"v" : ,
"key" : {
"sn" :
},
"ns" : "test.stu",
"name" : "sn_1"
}
] > db.stu.ensureIndex({sn:,name:});
>
>
> db.stu.getIndexes();
[
{
"v" : ,
"key" : {
"_id" :
},
"ns" : "test.stu",
"name" : "_id_"
},
{
"v" : ,
"key" : {
"sn" :
},
"ns" : "test.stu",
"name" : "sn_1"
},
{
"v" : ,
"key" : {
"sn" : ,
"name" :
},
"ns" : "test.stu",
"name" : "sn_1_name_1"
}
]

二. 子文档索引

     指向下级嵌套的文档的索引

 > db.shop.insert({name:'Nokia',spc:{weight:,area:'taiwan'}});
> db.shop.insert({name:'Nokia',spc:{weight:,area:'korea'}}); > db.shop.find({'spc.area':'taiwan'});
{ "_id" : ObjectId("5743d662addef29711337fb0"), "name" : "Nokia", "spc" : { "weight" : , "area" : "taiwan" } } > db.shop.ensureIndex({'spc.area,1'});
Tue May ::58.823 SyntaxError: Unexpected token }
> db.shop.ensureIndex({'spc.area':});
>
> db.shop.getIndexes();
[
{
"v" : ,
"key" : {
"_id" :
},
"ns" : "test.shop",
"name" : "_id_"
},
{
"v" : ,
"key" : {
"spc.area" :
},
"ns" : "test.shop",
"name" : "spc.area_1"
}
]
>

三.  唯一索引

 > show tables;
shop
stu
system.indexes
>
>
> db.tea.insert({email:'a@163.com'})
> db.tea.insert({email:'b@163.com'})
>
> db.tea.getIndexes();
[
{
"v" : ,
"key" : {
"_id" :
},
"ns" : "test.tea",
"name" : "_id_"
}
]
>
>
>
> db.tea.ensureIndex({email:},{unique:true});
>
>
> db.tea.insert({email:'c@163.com'})
> db.tea.insert({email:'c@163.com'})
E11000 duplicate key error index: test.tea.$email_1 dup key: { : "c@163.com" }
>

四. 稀疏索引

稀疏索引的特点------如果针对field做索引,针对不含field列的文档,将不建立索引.
与之相对,普通索引,会把该文档的field列的值认为NULL,并建索引.
适宜于: 小部分文档含有某列时.

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

 -- 模拟数据
> db.tea.insert({});
> db.tea.find();
{ "_id" : ObjectId("5743d98aaddef29711337fb4"), "email" : "a@163.com" }
{ "_id" : ObjectId("5743d98daddef29711337fb5"), "email" : "b@163.com" }
{ "_id" : ObjectId("5743d9cfaddef29711337fb7"), "email" : "c@163.com" }
{ "_id" : ObjectId("5743dc98addef29711337fbc") } --稀疏索引下查不到数据
> db.tea.ensureIndex({email:},{sparse:true});
> db.tea.find({email:null});
> > db.tea.dropIndexes();
{
"nIndexesWas" : ,
"msg" : "non-_id indexes dropped for collection",
"ok" :
} --普通索引能查到
> db.tea.ensureIndex({email:});
> db.tea.find({email:null});
{ "_id" : ObjectId("5743dc98addef29711337fbc") }

总结:
如果分别加普通索引,和稀疏索引,
对于最后一行的email分别当成null 和 忽略最后一行来处理.
根据{email:null}来查询,前者能查到,而稀疏索引查不到最后一行.

五. 创建哈希索引(2.4新增的)

哈希索引速度比普通索引快,但是,无能对范围查询进行优化.
适宜于---随机性强的散列

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

 > db.tea.ensureIndex({email:'hashed'});
> db.tea.find({email:'a@163.com'}).explain();
{
"cursor" : "BtreeCursor email_hashed",
"isMultiKey" : false,
"n" : ,
"nscannedObjects" : ,
"nscanned" : ,
"nscannedObjectsAllPlans" : ,
"nscannedAllPlans" : ,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : ,
"nChunkSkips" : ,
"millis" : ,
"indexBounds" : {
"email" : [
[
NumberLong(""),
NumberLong("")
]
]
},
"server" : "localhost.localdomain:27017"
}
>

六. 重建索引

一个表经过很多次修改后,导致表的文件产生空洞,索引文件也如此.
可以通过索引的重建,减少索引文件碎片,并提高索引的效率.
类似mysql中的optimize table

db.collection.reIndex()

 > db.tea.reIndex();
{
"nIndexesWas" : ,
"msg" : "indexes dropped for collection",
"nIndexes" : ,
"indexes" : [
{
"key" : {
"_id" :
},
"ns" : "test.tea",
"name" : "_id_"
},
{
"key" : {
"email" : "hashed"
},
"ns" : "test.tea",
"name" : "email_hashed"
}
],
"ok" :
}

MongoDB基础之六 索引的更多相关文章

  1. MongoDB学习笔记(索引)

    一.索引基础:    MongoDB的索引几乎与传统的关系型数据库一模一样,这其中也包括一些基本的优化技巧.下面是创建索引的命令:    > db.test.ensureIndex({" ...

  2. MongoDB学习笔记(索引)(转)

    一.索引基础:    MongoDB的索引几乎与传统的关系型数据库一模一样,这其中也包括一些基本的优化技巧.下面是创建索引的命令:    > db.test.ensureIndex({" ...

  3. MongoDB基础教程系列--未完待续

    最近对 MongoDB 产生兴趣,在网上找的大部分都是 2.X 版本,由于 2.X 与 3.X 差别还是很大的,所以自己参考官网,写了本系列.MongoDB 的知识还是很多的,本系列会持续更新,本文作 ...

  4. MongoDB 基础(2019年开篇)

    MongoDB基础知识: 1.什么是MongoDB NoSQL(NoSQL=Not Only SQL),意即"不仅仅是SQL". MongoDB是一个介于关系数据库和非关系数据库之 ...

  5. MongoDB基础学习

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  6. windows下mongodb基础玩法系列二CURD附加一

    windows下mongodb基础玩法系列 windows下mongodb基础玩法系列一介绍与安装 windows下mongodb基础玩法系列二CURD操作(创建.更新.读取和删除) windows下 ...

  7. MongoDB基础教程系列--目录结构

    最近对 MongoDB 产生兴趣,在网上找的大部分都是 2.X 版本,由于 2.X 与 3.X 差别还是很大的,所以自己参考官网,写了本系列.MongoDB 的知识还是很多的,本系列会持续更新,本文作 ...

  8. Mongodb 基础 查询表达式

    数据库操作 查看:show dbs; 创建:use dbname; // db.createCollection('collection_name');    隐式创建,需要创建的数据库中有表才表示创 ...

  9. Mongodb 笔记01 MongoDB 简介、MongoDB基础知识、启动和停止MongoDB

    MongoDB 简介 1. 易于使用:没有固定的模式,根据需要添加和删除字段更加容易 2. 易于扩展:MongoDB的设计采用横向扩展.面向文档的数据模型使它能很容易的再多台服务器之间进行分割.自动处 ...

随机推荐

  1. struts2使用iterator标签显示嵌套Map - 云自无心水自闲 - BlogJava

    ">            <s:iterator value="dataMap.keySet()" id="class">     ...

  2. Xcode崩溃问题调试 signal SIGABRT&EXC_BAD_ACCESS

    在进行app开发过程中会遇到很多的问题,各种崩溃令人相当头疼.当然,解决bug的能力也体现了一个程序员的水平,现在来说一说开发中经常遇到的崩溃问题吧. 常见崩溃问题: 一是signal SIGABRT ...

  3. xCode中如何安装旧的模拟器

    http://blog.csdn.net/cmengzhongren/article/details/50414493 这里给出如何把老版本的SDK加入到新的Xcode中的方法.其实很简单,就是将老版 ...

  4. Servlet实现文件上传(简单)(一)

     1..使用到的jar包,为apache的一个子项目  此commons-fileupload-1.2.2需要以下commons-io-2.0.1的支持   2.页面展示fileUpload.jsp ...

  5. PHP 判断几秒前,几分钟,几小时前

    PHP 对于时间的过了多久的判断,几秒前,几分钟前,几小时前,$time = strtotime("2017-01-15 14:42:00"); $time = strtotime ...

  6. MySql存储过程—7、游标(Cursor)

    |字号 订阅 1.游标的作用及属性 游标的作用就是用于对查询数据库所返回的记录进行遍历,以便进行相应的操作:游标有下面这些属性: a.游标是只读的,也就是不能更新它: b.游标是不能滚动的,也就是只能 ...

  7. EF 实体字段设置主键和自增

    [Key] //主键 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增 public int id { get; set; } ...

  8. UVa 357 - Let Me Count The Ways

    题目大意:也是硬币兑换问题,与147.674用同样的方法即可解决. #include <cstdio> #include <cstring> #define MAXN 3000 ...

  9. java系列--批量处理

    批量删除 批量更新 二.分页 1.基于sql语句 1).基于ROWID分页 2).基于RONUM分页 3).基于数据分析分页 2.基于结果集

  10. IM 融云 之 开发基础概念

    基础概念 - 开发篇 App Key / Secret App Key / Secret 相当于您的 App 在融云的账号和密码.是融云 SDK 连接服务器所必须的标识,每一个 App 对应一套 Ap ...