您的位置:首页 > 数据库 > Mongodb

MongoDB 索引

2017-10-29 11:17 225 查看
本文主要介绍了 MongoDB 的索引

默认利用btree来创建索引

1 相关操作

查看查询计划

db.stu.find(query).explain()
"cursor" : "BasicCursor",   --- 说明索引没有发挥作用
"nscannedObjects" : 1000,    --- 理论上要扫描多少行
"cursor" : "BtreeCursor sn_1",  -- 用到了btree索引


查看当前索引

db.student.getIndexes();


创建索引

db.student.ensureIndex({name:-1}) -- 降序创建索引


删除索引

db.student.dropIndex({name: -1}) -- 删除单个索引

db.student.dropIndexes();  -- 删除所有索引


2 多列创建索引

db.student.ensureIndex({sn:1, name:1})


上述创建的索引会把两个列的值绑定成一个整体来看

3 子文档索引

查询子文档:
db.shop.find({'spc.area': 'taiwan'}, {_id: 0})


给子文档添加文档:
db.shop.ensureIndex({'spc.area': 1});


4 索引性质

创建唯一索引:
db.teacher.ensureIndex({email:1},{unique: true})


创建稀疏索引:
db.teacher.ensureIndex({email: 1}, {sparse: true})


> db.teacher.find()
{ "_id" : ObjectId("5678c99fff917ea632e5a6ca"), "email" : "a@gmail.com" }
{ "_id" : ObjectId("5678c9a3ff917ea632e5a6cb"), "email" : "b@gmail.com" }
{ "_id" : ObjectId("5678ca14ff917ea632e5a6cd"), "email" : "c@gmail.com" }
{ "_id" : ObjectId("5678ca5fff917ea632e5a6cf") }


在上述 teacher 表中,最后一行没有 email 列,如果为 teacher 表分别加上普通索引和稀疏索引,对于最后一行的 email 字段来说,普通索引将其当做 null, 稀疏索引会忽略最后一行。根据条件
{email: nulll}
来查询的话,普通索引能查到,而稀疏索引查不到。

创建哈希索引:
db.teacher.ensureIndex({email: 1}, {sparse: true})


5 重建索引

一个表如果经过很多次修改后,导致表的文件产生空洞,索引文件也是可以通过索引的重建来提高索引的效率,这类似MySQL中的
optimize tbale


减少索引文件碎片

db.collections.reindex()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: