博客
关于我
MongoDB学习笔记(8)--索引及优化索引
阅读量:800 次
发布时间:2023-02-09

本文共 1515 字,大约阅读时间需要 5 分钟。

MongoDB 索引的使用与优化指南

MongoDB 索引基础

在 MongoDB 中,默认会为 _id 字段创建索引,这与传统的关系型数据库(如 MySQL)中的行为一致。索引可以看作是数据存储系统的一层抽象,各类存储系统都有类似的索引实现接口。理解索引的作用对于数据库性能优化至关重要。

基础索引操作

创建索引时,字段 age 可以指定升序(1)或降序({-1}):

db.t3.ensureIndex({ age: 1 })

查看所有索引:

db.t3.getIndexes()

需要注意的是,系统自动创建的 _id 索引无法删除。

在数据量较大时,创建索引会消耗大量资源,因此可以在后台执行:

db.t3.ensureIndex({ age: 1 }, { background: true })

文档索引

MongoDB 的索引支持文档类型字段,甚至可以在地址字段 addr 上创建索引:

db.factories.ensureIndex({ addr: 1 })

例如,可以通过地址字段 addr 进行查询:

db.factories.find({ addr: { city: "Beijing", state: "BJ" } })

但若查询字段顺序与索引顺序不一致,则可能无法利用索引:

db.factories.find({ addr: { state: "BJ", city: "Beijing" } })

组合索引

MongoDB 支持组合索引,可以同时对 addr.city 和 addr.state 索引:

db.factories.ensureIndex({ "addr.city": 1, "addr.state": 1 })

组合索引在以下场景中非常有用:

  • 查询地址信息时:
    db.factories.find({ "addr.city": "Beijing", "addr.state": "BJ" })
  • 按地址排序时:
    db.factories.find().sort({ "addr.city": 1, "addr.state": 1 })

需要注意索引字段顺序与查询字段顺序保持一致。

唯一索引

要创建唯一索引,需在 ensureIndex 命令中指定 unique: true:

db.t4.ensureIndex({ firstname: 1, lastname: 1 }, { unique: true })

强制使用索引

通过指定索引提示,可以强制使用索引:

db.t5.find({ age: { $lt: 30 } }).hint({ name: 1, age: 1 })

删除索引

删除表中的所有索引:

db.t3.dropIndexes()

删除特定索引:

db.t4.dropIndex({ firstname: 1 })

执行计划解释

MongoDB 提供 explain 命令以展示查询执行计划:

db.t5.find({ age: { $gt: 45 } }, { name: 1 }).explain()

explain 输出示例:

  • cursor:返回类型(如 BtreeCursor age_1)
  • nscanned:扫描的文档数
  • n:返回的文档数量
  • millis:执行时间(毫秒)
  • indexBounds:使用的索引信息

通过 explain 命令可以观察索引优化效果,并针对性优化数据库性能。

##字段说明

  • cursor:返回类型。
  • nscanned:被扫描的文档数。
  • n:返回的文档数量。
  • millis:耗时(毫秒)。
  • indexBounds:使用的索引信息。

转载地址:http://jnffk.baihongyu.com/

你可能感兴趣的文章
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>
python函数编写_[零基础学python]传说中的函数编写条规
查看>>
Python+selenium —— UI自动化之鼠标操作
查看>>
python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
查看>>
Python+Selenium+Threading进行兼容性测试
查看>>
Python+selenium+unittest的GUI自动化框架实现
查看>>
python函数拟合不规则曲线_Python计算&绘图——曲线拟合问题(转)
查看>>
python函数定义的基本格式_零基础学python-2.19 定义函数、调用函数与默认参数
查看>>
Python+Selenium之数据驱动测试的实现
查看>>
python函数定义与使用+返回值简解
查看>>
Python+Selenium登录
查看>>
Python日期时间模块
查看>>
Python函数合集:足足68个内置函数请收好!
查看>>
Python+Selenium自动化测试项目实战
查看>>
Python+Selenium自动化测试项目实战【建议收藏】
查看>>
Python+Selenium自动化测试:Page Object模式
查看>>
python+selenium进行cnblog的自动化登录测试
查看>>
Python函数只返回第一个值而不是数据框
查看>>
Python+SQL实战:京东用户行为数据分析案例解析(上)
查看>>