MongoDB数据库索引用法详解

 更新时间:2022年07月08日 16:27:05   作者:奋斗的大橙子  
本文详细讲解了MongoDB数据库索引的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

一.索引详讲

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

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

> 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

> 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建立一个索引

db.books.ensureIndex({number:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> 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文档

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

> 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;
... }

不进行添加索引的时候:

> var x = time();
> x
63057

创建索引

> db.books.ensureIndex({number:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

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

> var x = time();
> x
67223

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

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

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

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

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

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

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

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

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

4.详细介绍索引的创建

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

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

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

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

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

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

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

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

> 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})

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

> 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属性来进行删除重复的数据

> db.books.ensureIndex({name:1},{unique:true,dropDups:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>

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

> 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中建立一个拥有很多坐标点的文档

> 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个点

> 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)为对角线的正方形中的所有的点

> 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规则下的圆心面积中的点

> 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数据库索引用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

相关文章

  • MongoDB索引使用详解

    MongoDB索引使用详解

    索引,使用索引可快速访问数据库表中的特定信息。索引是对数据库表中一列或多列的值进行排序的一种结构,例如 employee 表的姓名(name)列。如果要按姓查找特定职员,与必须搜索表中的所有行相比,索引会帮助您更快地获得该信息。
    2016-01-01
  • Mongodb常见操作符和运算符总结

    Mongodb常见操作符和运算符总结

    MongoDB 提供了丰富的操作符(Operators)和运算符(Expressions)用于在查询和更新文档时指定条件和操作数据,本文将通过代码示例给大家详细的总结一下Mongodb常见操作符和运算符,需要的朋友可以参考下
    2024-01-01
  • MongoDB日志文件过大的解决方法

    MongoDB日志文件过大的解决方法

    这篇文章主要介绍了MongoDB日志文件过大的解决方法,本文给出了一种不需要重启MongoDB服务的方法重新开启一个新日志文件,需要的朋友可以参考下
    2014-10-10
  • MongoDB创建和查询视图的方式

    MongoDB创建和查询视图的方式

    本文整理mongodb的官方文档,介绍mongodb的视图创建和查询,在Mongodb中,允许使用两种方式来创建视图,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2023-12-12
  • MongoDB中实现多表联查的实例教程

    MongoDB中实现多表联查的实例教程

    数据库应用在我们的生活中是很常见的,在编辑一些应用以及软件的时候都需要用到数据库来存储数据,下面这篇文章主要给大家介绍了关于MongoDB中实现多表联查的相关资料,需要的朋友可以参考下
    2022-07-07
  • 修复 Mac brew 安装 mongodb 报 Error: No available formula with the name ‘mongodb’ 问题详解

    修复 Mac brew 安装 mongodb 报 Error: No available formula with th

    最近在同事新的 Mac 电脑上安装 mongodb,报了错误 Error: No available formula with the name ‘mongodb’,今天就说说这个问题如何解决,需要的朋友可以参考下
    2020-02-02
  • MongoDB按时间分组操作实战

    MongoDB按时间分组操作实战

    MongoDB支持使用聚合操作来统计数据,下面这篇文章主要给大家介绍了关于MongoDB按时间分组操作的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • MongoDB中创建索引需要注意的事项

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

    这篇文章主要介绍了MongoDB中创建索引需要注意的事项,本文讲解了创建索引可能会引发的问题并给出解决方法,需要的朋友可以参考下
    2015-03-03
  • mongodb 命令行下及php中insert数据详解

    mongodb 命令行下及php中insert数据详解

    这篇文章主要介绍了mongodb 命令行下及php中insert数据详解,需要的朋友可以参考下
    2014-07-07
  • MongoDB快速入门笔记(三)之MongoDB插入文档操作

    MongoDB快速入门笔记(三)之MongoDB插入文档操作

    这篇文章主要介绍了MongoDB快速入门笔记(三)之MongoDB插入文档操作 的相关资料,非常不错具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06

最新评论

?


http://www.vxiaotou.com