mongo索引

本文主要介绍mongo的索引

  • 索引的作用
  • 索引的类型
  • 索引的注意事项
  • 索引的创建管理

索引的作用
索引的作用是在进行查询的时候,首先会去查询索引,如果在索引中找到对应的内容,那么根据索引对应的地址找到相应的数据即可,从而加快查询的速度。不过,每次在进行插入操作的时候会更新索引对应的B树。所以需要根据需要创建索引,不要创建不必要的索引。

索引的类型
  • 单键索引
  • 复合索引
  • 唯一索引
  • 稀疏索引


索引创建的注意事项
1、如果collections不是很大,不推荐建索引,因为这样会在每个查询的时候发生两次查找,一次是查找索引,一次是找表。
2、如果某个索引是为了管理员平时维护数据使用的索引,最好不要建立出来。建立索引的时候,最好是为程序中已经使用的一些查询创建索引。

查看索引
db.COLLECTION.getIndexKeys();
db.COLLECTION.getIndices();

创建索引
>db.user.ensureIndex({"name":1})

{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}

> db.user.getIndexKeys();
[ { "_id" : 1 }, { "name" : 1 } ]

创建复合索引
db.user.ensureIndex({"name":1,"age":1})


重建索引
> db.user.reIndex({"name":1});
{
"nIndexesWas" : 2,
"nIndexes" : 2,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "xytest.user"
},
{
"v" : 2,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "xytest.user"
}
],
"ok" : 1
}


删除索引
db.dropIndex("name_1")

猜你喜欢

转载自blog.csdn.net/wild46cat/article/details/80161239