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

你可能感兴趣的文章
MongoDB 对索引的创建查询修改删除 附代码
查看>>
MSSQL数据库日志满的快速解决办法
查看>>
MongoDB 性能调优
查看>>
MongoDB 文档字段增删改
查看>>
MongoDB 核心技术详解
查看>>
MongoDB 系统管理与操作详解
查看>>
mongoDB 索引
查看>>
MongoDB 聚合
查看>>
mongodb 集群shard_MongoDB Sharding Cluster 分片集群搭建及使用
查看>>
mongodb 默认端口号_MongoDB的简单使用
查看>>
mongodb-地理坐标存储查询
查看>>
MongoDB与Mysql常用命令解释
查看>>
MongoDB两地三中心集群架构设计、全球多写集群架构设计
查看>>
mongodb中比较级查询条件:($lt $lte $gt $gte)(大于、小于)、查找条件
查看>>
Mongodb中的聚合函数使用:按月统计数量
查看>>
Mongodb主从配置
查看>>
Mongodb事务:基于spring+springmvc
查看>>
mongodb使用总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
Mongodb出现Error: couldn‘t add user: Could not find role: root@database 解决方法
查看>>