服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - MongoDB数据库索引用法详解

MongoDB数据库索引用法详解

2022-07-09 08:39奋斗的大橙子 MongoDB

本文详细讲解了MongoDB数据库索引的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一.索引详讲

索引是什么,索引就好比一本书的目录,当我们想找某一章节的时候,通过书籍的目录可以很快的找到,所以适当的加入索引可以提高我们查询的数据的速度。

准备工作,向MongoDB中插入20000条记录,没条记录都有number和name

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> for(var i = 0 ; i<200000 ;i++){
... db.books.insert({number:i,name:"book"+i})
... }
WriteResult({ "nInserted" : 1 })
> db.books.find({},{_id:0})
{ "number" : 0, "name" : "book0" }
{ "number" : 1, "name" : "book1" }
{ "number" : 2, "name" : "book2" }
{ "number" : 3, "name" : "book3" }
{ "number" : 4, "name" : "book4" }
{ "number" : 5, "name" : "book5" }
{ "number" : 6, "name" : "book6" }
{ "number" : 7, "name" : "book7" }
……
>

1.对比加入索引和不加入索引的查询效率

例:查询number为65535的name

不使用索引的情况下,查询时间请看millis

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> db.books.find({number:65535},{_id:0,name:1}).explain()
{
        "cursor" : "BasicCursor",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 200000,
        "nscanned" : 200000,
        "nscannedObjectsAllPlans" : 200000,
        "nscannedAllPlans" : 200000,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 1562,
        "nChunkSkips" : 0,
        "millis" : 172,
        "server" : "G08FNSTD131598:27017",
        "filterSet" : false
}
>

使用索引的情况下,先创建一个简单索引,用number建立一个索引

?
1
2
3
4
5
6
7
db.books.ensureIndex({number:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
> db.books.find({number:65535},{_id:0,name:1}).explain()
{
        "cursor" : "BtreeCursor number_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
"indexBounds" : {
                "number" : [
                        [
                                65535,
                                65535
                        ]
                ]
        },
        "server" : "G08FNSTD131598:27017",
        "filterSet" : false
}
>

从上面可以看到,查询的时间上带索引的情况要有明显的缩短

2.从插入的数据的时间上进行对比

准备工作,删除刚刚建立的books文档

定义一个函数,来完成记录时间和插入数据的操作

?
1
2
3
4
5
6
7
8
> var time = function(){
... var start = new Date();
... for(var i = 0;i < 200000 ; i++){
... db.books.insert({number:i,name:"book"+i});
... }
... var end = new Date();
... return end - start;
... }

不进行添加索引的时候:

?
1
2
3
> var x = time();
> x
63057

创建索引

?
1
2
3
4
5
6
7
> db.books.ensureIndex({number:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

存在索引的时候的插入数据所用的时间

?
1
2
3
> var x = time();
> x
67223

可以看到不存在索引的时候,插入的数据所用的时间较短

综上:当我们对一个文档需要进行频繁的插入操作的时候,建立不巧当的索引会导致插入效率的降低。

3.建立索引需要注意的地方

创建索引的时候注意1是正序创建索引-1是倒序创建索引

索引的创建在提高查询性能的同事会影响插入的性能

对于经常查询少插入的文档可以考虑用索引

符合索引要注意索引的先后顺序

每个键全建立索引不一定就能提高性能呢,索引不是万能的

在做排序工作的时候如果是超大数据量也可以考虑加上索引用来提高排序的性能

4.详细介绍索引的创建

①在创建索引的时候,使用了ensureIndex()这个方法,使用它会创建索引,名字就是键的名字加上一个数字,例如number_1或者number_-1,其中1代表是正序索引,-1代表逆序索引

②如果觉得1或-1比较不容易记,还可以使用自定义名字来创建索引

?
1
2
3
4
5
6
7
> db.books.ensureIndex({name:1},{name:"bookNameIndex"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}

③一个文档建立了多个索引,但是我又想强制使用其中的一个索引,怎么办

例如,我在上面的文档中对number建立了逆序索引,对name建立了正序索引,现在我想查找的时候用name进行索引,我应该这么写:

?
1
2
3
4
> db.books.find({name:"book2016"},{_id:0}).hint({name:1})
{ "number" : 2016, "name" : "book2016" }
{ "number" : 2016, "name" : "book2016" }
>

如果使用了没有创建的索引,那么会返回一个“bad hint”的错误。

④查看所用的索引和查询数据状态信息,可以使用explain()方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
> db.books.find({name:"book2016"},{_id:0}).hint({name:1}).explain()
{
        "cursor" : "BtreeCursor bookNameIndex",
        "isMultiKey" : false,
        "n" : 2,
        "nscannedObjects" : 2,
        "nscanned" : 2,
        "nscannedObjectsAllPlans" : 2,
        "nscannedAllPlans" : 2,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "name" : [
                        [
                                "book2016",
                                "book2016"
                        ]
                ]
        },
        "server" : "G08FNSTD131598:27017",
        "filterSet" : false
}

上面看到,我们的索引的名字是bookNameIndex,并且millis是0,nscanned是查到了几个文档

⑤在关系型数据库中尝尝会有约束条件,比较常用的就是唯一性,在MongoDB中也可以指定唯一

建立唯一索引:db.books.ensureIndex({name:-1},{unique:true})

上面我通过有索引和无索引插入了两组完全一样的数据,此时如果去建立唯一的索引,那么就会出错

?
1
2
3
4
5
6
7
8
9
> db.books.ensureIndex({name:1},{unique:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "ok" : 0,
        "errmsg" : "E11000 duplicate key error index: mongoDBTest.books.$name_1
 dup key: { : \"book0\" }",
        "code" : 11000
}

此时可以通过dropDups:true属性来进行删除重复的数据

?
1
2
3
4
5
6
7
8
> db.books.ensureIndex({name:1},{unique:true,dropDups:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>

删除重复之后,再去加入一个相同名字的数据,就会出现下面的情况

?
1
2
3
4
5
6
7
8
9
10
> db.books.insert({number:1,name:"book1"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicat
e key error index: mongoDBTest.books.$name_1  dup key: { : \"book1\" }"
        }
})
>

⑥删除索引

指定要删除的索引

db.runCommand({dropIndexes : ”books” , index:”name_-1”})

删除所有的索引

db.runCommand({dropIndexes : ”books” , index:”*”})

注意:索引的创建时同步的,所以如果想指定异步的去创建索引,就要指定在后台去创建

db.books.ensureIndex({name:-1},{background:true})

二.空间索引

2D索引,举例在一片区域中建立坐标系,那么很多地点可以看做是一个个的坐标,此时2d索引就可以帮助我们进行快速的查询某一个范围的地点了。

例:我在MongoDB中建立一个拥有很多坐标点的文档

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> db.map.find({},{_id:0})
{ "gis" : { "x" : 185, "y" : 150 } }
{ "gis" : { "x" : 70, "y" : 180 } }
{ "gis" : { "x" : 75, "y" : 180 } }
{ "gis" : { "x" : 185, "y" : 185 } }
{ "gis" : { "x" : 65, "y" : 185 } }
{ "gis" : { "x" : 50, "y" : 50 } }
{ "gis" : { "x" : 50, "y" : 100 } }
{ "gis" : { "x" : 60, "y" : 55 } }
{ "gis" : { "x" : 65, "y" : 80 } }
{ "gis" : { "x" : 55, "y" : 80 } }
{ "gis" : { "x" : 0, "y" : 0 } }
{ "gis" : { "x" : 0, "y" : 200 } }
{ "gis" : { "x" : 200, "y" : 0 } }
{ "gis" : { "x" : 200, "y" : 200 } }
>

添加一个2D索引

db.map.ensureIndex({"gis":"2d"},{min:-1,max:201})

默认会建立一个[-180,180]之间的2D索引

例子:

①查询点(70,180)最近的3个点

?
1
2
3
4
> db.map.find({"gis":{$near:[70,180]}},{gis:1,_id:0}).limit(3)
{ "gis" : { "x" : 70, "y" : 180 } }
{ "gis" : { "x" : 75, "y" : 180 } }
{ "gis" : { "x" : 65, "y" : 185 } }

②查询以点(50,50)和点(190,190)为对角线的正方形中的所有的点

?
1
2
3
4
5
6
7
8
9
10
11
12
> db.map.find({gis:{$within:{$box:[[50,50],[190,190]]}}},{_id:0,gis:1})
{ "gis" : { "x" : 185, "y" : 150 } }
{ "gis" : { "x" : 75, "y" : 180 } }
{ "gis" : { "x" : 70, "y" : 180 } }
{ "gis" : { "x" : 65, "y" : 185 } }
{ "gis" : { "x" : 50, "y" : 100 } }
{ "gis" : { "x" : 65, "y" : 80 } }
{ "gis" : { "x" : 55, "y" : 80 } }
{ "gis" : { "x" : 60, "y" : 55 } }
{ "gis" : { "x" : 50, "y" : 50 } }
{ "gis" : { "x" : 185, "y" : 185 } }
>

③查询出以圆心为(56,80)半径为50规则下的圆心面积中的点

?
1
2
3
4
5
6
> db.map.find({gis:{$within:{$center:[[56,80],50]}}},{_id:0,gis:1})
{ "gis" : { "x" : 55, "y" : 80 } }
{ "gis" : { "x" : 50, "y" : 100 } }
{ "gis" : { "x" : 50, "y" : 50 } }
{ "gis" : { "x" : 60, "y" : 55 } }
{ "gis" : { "x" : 65, "y" : 80 } }

到此这篇关于MongoDB数据库索引用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/dcz2015/p/5258577.html

延伸 · 阅读

精彩推荐
  • MongoDBMongoDB如何查询耗时记录的方法详解

    MongoDB如何查询耗时记录的方法详解

    查询操作是我们日常操作数据库经常会遇到的一个功能,下面这篇文章主要给大家介绍了关于MongoDB如何查询耗时记录的相关资料,文中通过示例代码介绍的...

    Chain8272020-05-15
  • MongoDBMongoDB中游标的深入学习

    MongoDB中游标的深入学习

    MongoDB中find()函数返回一个游标,客户端通过对游标进行一些设置就能对查询结果进行有效地控制,如可以限制查询得到的结果数量、跳过部分结果、或对结...

    Leshami1692020-05-10
  • MongoDBMongoDB的一些常用查询方法

    MongoDB的一些常用查询方法

    这篇文章主要介绍了MongoDB的一些常用查询方法,本文罗列了MongoDB的一些常见、常用查询方法,非常的实用,需要的朋友可以参考下 ...

    MongoDB教程网6252020-05-03
  • MongoDBwindow平台安装MongoDB数据库图文详解

    window平台安装MongoDB数据库图文详解

    本篇文章主要介绍了window平台安装MongoDB数据库图文详解,主要介绍window下面安装mogod的步骤和使用细节。感兴趣的小伙伴们可以参考一下。 ...

    tinyphp3092020-05-09
  • MongoDBMongodb启动命令参数中文说明

    Mongodb启动命令参数中文说明

    这篇文章主要介绍了Mongodb启动命令参数中文说明,本文包括基本配置、主/从参数、Sharding(分片)选项等内容,需要的朋友可以参考下 ...

    MongoDB教程网2472020-04-29
  • MongoDBMongoDB中创建索引需要注意的事项

    MongoDB中创建索引需要注意的事项

    这篇文章主要介绍了MongoDB中创建索引需要注意的事项,本文讲解了创建索引可能会引发的问题并给出解决方法,需要的朋友可以参考下 ...

    MongoDB之家5832020-04-30
  • MongoDBMongoDB集合的增删改查管理

    MongoDB集合的增删改查管理

    这篇文章介绍了MongoDB集合的增删改查管理,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    社会主义接班人7282022-07-07
  • MongoDBMongoDB学习笔记—Linux下搭建MongoDB环境

    MongoDB学习笔记—Linux下搭建MongoDB环境

    本篇文章主要介绍了Linux下搭建MongoDB环境,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...

    Kencery2352020-05-09