当前位置: 首页 > article >正文

第4章:MongoDB索引

第4章:MongoDB索引

4.1 索引基础

4.1.1 索引的重要性

  • 提高查询性能
  • 减少集合扫描
  • 支持高效排序

4.1.2 默认索引

// _id字段的默认索引
{
    "_id": ObjectId("..."),
    "name": "示例文档"
}

4.2 索引类型

4.2.1 单字段索引

// 创建单字段索引
db.users.createIndex({username: 1})  // 升序
db.users.createIndex({username: -1}) // 降序

// 查看集合索引
db.users.getIndexes()

4.2.2 复合索引

// 创建复合索引
db.users.createIndex({
    lastName: 1, 
    firstName: 1
})

// 复合索引查询
db.users.find().sort({
    lastName: 1, 
    firstName: 1
})

4.2.3 唯一索引

// 创建唯一索引
db.users.createIndex(
    {email: 1}, 
    {unique: true}
)

// 部分唯一索引
db.users.createIndex(
    {username: 1},
    {
        unique: true,
        partialFilterExpression: {age: {$gt: 18}}
    }
)

4.2.4 文本索引

// 创建文本索引
db.articles.createIndex(
    {content: "text"},
    {
        weights: {
            content: 10,
            tags: 5
        },
        name: "content_text_index"
    }
)

// 文本搜索
db.articles.find({
    $text: {$search: "MongoDB 数据库"}
})

4.2.5 地理空间索引

// 创建2dsphere索引
db.places.createIndex({location: "2dsphere"})

// 地理位置查询
db.places.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [116.4, 39.9]
            },
            $maxDistance: 1000
        }
    }
})

4.3 索引性能分析

4.3.1 查询执行计划

// 分析查询性能
db.users.find({username: "example"}).explain("executionStats")

// 查看索引使用情况
db.users.find({username: "example"}).hint({username: 1})

4.3.2 索引选择策略

// 创建复合索引
db.products.createIndex({
    category: 1, 
    price: -1
})

// 高效查询
db.products.find({
    category: "电子产品",
    price: {$gt: 1000}
}).sort({price: -1})

4.4 索引管理

4.4.1 索引操作

// 删除指定索引
db.users.dropIndex({username: 1})

// 删除所有索引(除_id)
db.users.dropIndexes()

// 重建索引
db.users.reIndex()

4.4.2 后台创建索引

// 后台创建索引(不阻塞写操作)
db.users.createIndex(
    {username: 1}, 
    {background: true}
)

4.5 常见索引问题

4.5.1 索引开销

  • 写入性能下降
  • 额外存储空间
  • 定期评估和调整

4.5.2 最佳实践

  1. 仅为常用查询创建索引
  2. 避免过多索引
  3. 使用复合索引替代多个单字段索引
  4. 定期分析和优化

http://www.kler.cn/a/469306.html

相关文章:

  • 【React+TypeScript+DeepSeek】穿越时空对话机
  • WPF区域导航+导航参数使用+路由守卫+导航日志
  • axios和fetch的实现原理以及区别,与XMLHttpRequest的关系,并结合react封装统一请求示例
  • 安装Linux
  • 【C++】B2091 向量点积计算
  • 【stm32+K210项目】基于K210与STM32协同工作的智能垃圾分类系统设计与实现(完整工程资料源码)
  • JavaWeb开发(六)XML介绍
  • 使用WebSocket 获取实时数据
  • 06-C++类和对象强化
  • UDP接收和断线重连代码注入案例
  • vue使用树形结构展示文件和文件夹
  • 港大发布OpenCity: 大模型驱动下的智慧城市“新内核“
  • 关于python的数据分析与应用
  • Linux上vi(vim)编辑器使用教程
  • MYSQL---------支持数据类型
  • unity中的UI系统---GUI
  • 如何使用Termux 通过 SSH 连接到远程服务器
  • vue3 如何封装aixos
  • 【AI数学基础】线性代数:内积和范数
  • 换肤-主题:使用 CSS 自定义属性 -- var()函数 详解