博客
关于我
MongoDB学习笔记(8)--索引及优化索引
阅读量:798 次
发布时间: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.cityaddr.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/

你可能感兴趣的文章
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>