MongoDB-CN-Manual
  • MongoDB中文手册|官方文档中文版
  • MongoDB用户手册说明
  • MongoDB简介
    • 入门
    • 数据库和集合
      • 视图
      • 按需物化视图
      • 封顶集合
      • 时间序列集合
    • 文档
    • BSON类型
      • Comparison and Sort Order
      • MongoDB Extended JSON (v2)
      • MongoDB Extended JSON (v1)
  • 安装 MongoDB
    • 安装MongoDB社区版
      • 在Linux上安装MongoDB社区版
      • 在macOS上安装MongoDB社区版
      • 在Windows上安装MongoDB社区版
    • 安装MongoDB企业版
      • 在Linux上安装MongoDB企业版
      • 在Mac OS安装MongoDB企业版
      • 在Windows安装MongoDB企业版
      • 使用Docker安装MongoDB企业版
    • 将社区版MongoDB升级到企业版MongoDB
    • 验证MongoDB软件包的完整性
  • The mongo Shell
    • 配置mongo Shell
    • 使用 mongo Shell帮助
    • 为mongo Shell编写脚本
    • mongo Shell中的数据类型
    • mongo Shell 快速参考
  • MongoDB CRUD操作
    • 插入文档
      • 插入方法
    • 查询文档
      • 在mongo Shell中迭代游标
      • 从查询返回的项目字段
      • 查询嵌入式文档数组
      • 查询数组
      • 查询空字段或缺少字段
      • 查询嵌入/嵌套文档
    • 更新文档
      • 更新方法
      • 聚合管道更新
    • 删除文档
      • 删除方法
    • 地理空间查询
      • 用地理空间查询查找餐馆
      • GeoJSON对象
    • 批量写入操作
    • 可重试写入
    • 可重试读取
    • SQL到MongoDB的映射图表
    • 文本搜索
      • 文本索引
      • 文本索引操作
      • 集合管道中的文本索引
      • 文本索引语言
    • Read Concern读关注
      • 读关注 "local"
      • 读关注 "available"
      • 读关注 "majority"
      • 读关注 "linearizable"
      • 读关注 "snapshot"
    • Write Concern写关注
    • MongoDB CRUD概念
      • 原子性和事务
      • 读隔离性,一致性和近因性
        • 因果一致性和读写关注
      • 分布式查询
      • 通过findAndModify进行线性化读取
      • 查询计划
      • 查询优化
        • 评估当前操作性能
        • 优化查询性能
        • 写操作性能
        • 说明结果
      • 分析查询表现
      • Tailable 游标
  • MongoDB聚合
    • 聚合管道
      • 聚合管道优化
      • 聚合管道限制
      • 聚合管道和分片集合
      • 使用 Zip Code 数据集进行聚合
      • 使用用户首选项数据进行聚合
    • Map-Reduce
      • Map-Reduce 和分片集合
      • Map-Reduce 并发
      • Map-Reduce 示例
      • 执行增量 Map-Reduce
      • 对 Map Function 进行故障排除
      • 排除 Reduce Function 问题
      • Map-Reduce转换到聚合管道
    • 聚合参考
      • 聚合管道快速参考
      • 聚合命令
      • 聚合命令对比
      • 聚合表达式中的变量
      • SQL 到聚合映射图表
  • MongoDB数据模型
    • 数据建模介绍
    • 模式验证
    • 数据模型设计
      • 一对一嵌套关系模型
  • MongoDB事务
  • MongoDB事务
    • 驱动程序 API
    • 生产注意事项
    • 生产注意事项 (分片集群)
    • 事务操作
  • MongoDB索引
    • 单字段索引
    • 复合索引
    • 多键索引
      • 多键索引范围
    • 文本索引
      • 为文本索引指定语言
      • 指定文本索引的名称
      • 用权重控制搜索结果
      • 限制扫描条目的数量
    • 通配符索引
      • 通配符索引限制
    • 2dsphere 索引
      • 查询一个2dsphere索引
    • 2d 索引
      • 创建一个2d索引
      • 查询一个2d索引
      • 2d索引内部
      • 使用球面几何计算距离
    • geoHaystack 索引
      • 创建Haystack索引
      • 查询Haystack索引
    • 哈希索引
    • 索引特性
      • TTL 索引
        • 通过设置TTL使集合中的数据过期
      • 唯一索引
      • 部分索引
      • 不分大小写索引
      • Sparse 索引
    • 在填充的集合上建立索引
      • 在副本集上建立滚动索引
      • 在分片群集上建立滚动索引
    • 索引交集
    • 管理索引
    • 衡量索引使用
    • 索引策略
      • 创建索引来支持查询
      • 使用索引对查询结果进行排序
      • 确保索引适合RAM
      • 创建以确保选择性的查询
    • 索引参考
  • MongoDB安全
    • 安全检查列表
    • 启用访问控制
    • 身份验证
      • 用户
        • 添加用户
        • 权限认证机制
          • SCRAM
            • 用x.509证书来认证客户端
    • 审计
      • 配置审计过滤器
      • 配置审计
      • 系统事件审计消息
    • 网络和配置强化
    • 安全参考
      • system.roles集合
      • system.users集合
      • 资源文档
      • 权限操作
    • 附录
      • 附录-A-用于测试的 OpenSSl CA 证书
      • 附录-B-用于测试的OpenSSL服务器证书
      • 附录-C-用于测试的OpenSSL客户端证书
  • Change Streams变更流
    • 变更流生产建议
    • 变更事件
  • MongoDB复制
    • 副本集成员
    • 副本集日志
    • 副本集数据同步
    • 副本集部署架构
    • 副本集成员配置教程
    • 副本集维护教程
    • MongoDB复制参考
  • MongoDB分片
    • 分片集群组件
    • 分片键
    • 哈希分片
    • 范围分片
    • 区
      • 管理分片区
      • 按位置细分数据
      • 用于更改SLA或SLO的分层硬件
      • 按应用或客户细分数据
      • 仅插入工作负载的分布式本地写入
      • 管理分片区
    • 使用块进行数据分区
      • 在分片集群中拆分数据块
    • 分片管理
      • 查看集群设置
    • 重启一个分片集群
    • [把一个分片集群迁移到不同的硬件](fen-pian/migrate-a -sharded-cluster-to-different-hardware.md)
    • 分片参考
  • MongoDB管理
    • 产品说明
    • 操作检查列表
    • 开发检查列表
    • 配置和维护
    • 性能
    • 数据中心意识
      • MongoDB部署中的工作负载隔离
      • 区
        • 管理分片区
        • 按位置细分数据
        • 用于更改SLA或SLO的分层硬件
        • 按应用或客户细分数据
        • 仅插入工作负载的分布式本地写入
        • 管理分片区
    • MongoDB备份方法
    • MongoDB监控
  • MongoDB存储
    • 存储引擎
      • WiredTiger 存储引擎
      • 内存存储引擎
    • 日志记录
      • 管理日志记录
        • GridFS
        • FAQ:MongoDB 存储
  • MongoDB参考
    • 运算符
      • 查询与映射运算符
        • 比较查询运算符
          • $eq
          • $gt
          • $gte
          • $in
          • $lt
          • $lte
          • $ne
          • $nin
        • 逻辑查询运算符
          • $and
          • $not
          • $nor
          • $or
        • 元素查询运算符
        • 评估查询运算符
        • 地理空间查询运算符
        • 数组查询运算符
        • 按位查询运算符
        • $comment
        • 映射运算符
      • 更新运算符
        • 字段更新运算符
        • 数组更新运算符
        • 按位更新运算符
      • 聚合管道阶段
      • 聚合管道操作符
        • $abs (aggregation)
        • $acos (aggregation)
        • $acosh (aggregation)
        • $add (aggregation)
        • $addToSet (aggregation)
        • $allElementsTrue (aggregation)
        • $and (aggregation)
        • $anyElementTrue (aggregation)
        • $arrayElemAt (aggregation)
        • $arrayToObject (aggregation)
        • $asin (aggregation)
        • $asinh (aggregation)
        • $atan (aggregation)
        • $atan2 (aggregation)
        • $atanh (aggregation)
        • $avg (aggregation)
        • $ceil (aggregation)
        • $cmp (aggregation)
        • $concat (aggregation)
        • $concatArrays (aggregation)
        • $cond (aggregation)
        • $convert (aggregation)
        • $cos (aggregation)
        • $dateFromParts (aggregation)
        • $dateToParts (aggregation)
        • $dateFromString (aggregation)
        • $literal (aggregation)
      • 查询修饰符
    • 数据库命令
      • 聚合命令
      • 地理空间命令
      • 查询和写操作命令
      • 查询计划缓存命令
      • 认证命令
      • 用户管理命令
      • 角色管理命令
      • 复制命令
      • 分片命令
      • 会话命令
      • 管理命令
      • 诊断命令
      • 免费监控命令
      • 系统事件审计命令
    • mongo Shell 方法
      • 集合方法
        • db.collection.aggregate()
        • db.collection.bulkWrite()
        • db.collection.copyTo()
        • db.collection.count()
        • db.collection.countDocuments()
        • db.collection.estimatedDocumentCount()
        • db.collection.createIndex()
        • db.collection.createIndexes()
        • db.collection.dataSize()
        • db.collection.deleteOne()
        • db.collection.deleteMany()
        • db.collection.distinct()
        • db.collection.drop()
        • db.collection.dropIndex()
        • db.collection.dropIndexes()
        • db.collection.ensureIndex()
        • db.collection.explain()
        • db.collection.find()
        • db.collection.findAndModify()
        • db.collection.findOne()
        • db.collection.findOneAndDelete()
        • db.collection.findOneAndReplace()
        • db.collection.findOneAndUpdate()
        • db.collection.getIndexes()
        • db.collection.getShardDistribution()
        • db.collection.getShardVersion()
        • db.collection.insert()
        • db.collection.insertOne()
        • db.collection.insertMany()
        • db.collection.isCapped()
        • db.collection.latencyStats()
        • db.collection.mapReduce()
        • db.collection.reIndex()
        • db.collection.remove()
        • db.collection.renameCollection()
        • db.collection.replaceOne()
        • db.collection.save()
        • db.collection.stats()
        • db.collection.storageSize()
        • db.collection.totalIndexSize()
        • db.collection.totalSize()
        • db.collection.update()
        • db.collection.updateOne()
        • db.collection.updateMany()
        • db.collection.watch()
        • db.collection.validate()
    • MongoDB中的限制与阈值
    • MongoDB系统集合
    • 词汇表
    • 默认的MongoDB端口
    • 默认的MongoDB读/写关注
    • 服务器会话
  • MongoDB FAQ
    • FAQ: MongoDB基础知识
    • FAQ: MongoDB索引
    • FAQ: MongoDB并发
    • FAQ: MongoDB分片
    • FAQ: MongoDB复制和副本集
    • FAQ: MongoDB存储
    • FAQ: MongoDB诊断
  • MongoDB 版本管理
  • 联系我们
    • Tapdata Cloud
    • MongoDB中文社区
    • 社区合作伙伴—锦木信息
由 GitBook 提供支持
在本页
  • 查看现有索引
  • 列出集合上的所有索引
  • 列出数据库的所有索引
  • 列出特定类型的索引
  • 删除索引
  • 删除特定的指数
  • 删除所有索引
  • 修改索引
  • 在分片中查找不一致的索引
  1. MongoDB索引

管理索引

上一页索引交集下一页衡量索引使用

最后更新于3年前

  • Mongo Shell

在本页面

此页显示如何管理现有索引。有关创建索引的说明,请参阅特定索引类型页。

查看现有索引

以下部分提供了查看集合或整个数据库上现有索引的方法。

列出集合上的所有索引

要返回一个集合上所有索引的列表,使用方法或类似的。

例如,要查看people集合上的所有索引,运行以下命令:

db.people.getIndexes()

列出数据库的所有索引

在 shell中,可以使用以下操作列出数据库中所有的集合索引:

db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});

从3.0版本开始,MongoDB不再支持对系统的直接访问。索引集合,以前用于列出数据库中的所有索引。

列出特定类型的索引

// The following finds all hashed indexes

db.adminCommand("listDatabases").databases.forEach(function(d){
   let mdb = db.getSiblingDB(d.name);
   mdb.getCollectionInfos({ type: "collection" }).forEach(function(c){
      let currentCollection = mdb.getCollection(c.name);
      currentCollection.getIndexes().forEach(function(idx){
        let idxValues = Object.values(Object.assign({}, idx.key));

        if (idxValues.includes("hashed")) {
          print("Hashed index: " + idx.name + " on " + idx.ns);
          printjson(idx);
        };
      });
   });
});

删除索引

MongoDB提供了两种方法从集合中删除索引:

删除特定的指数

例如,下面的操作删除了 accounts 集合中的 tax-id 字段的升序索引:

db.accounts.dropIndex( { "tax-id": 1 } )

该操作返回一个文档,其中显示了该操作的状态:

{ "nIndexesWas" : 3, "ok" : 1 }

其中nIndexesWas的值反映了_在删除这个索引之前_的索引数量。

注意

删除所有索引

例如,下面的命令从 accounts 集合中删除所有索引:

db.accounts.dropIndexes()

修改索引

在分片中查找不一致的索引

如果分片集合在每个包含该分片块的分片上没有完全相同的索引(包括索引选项),则该集合具有不一致的索引。虽然在正常操作中不应该出现索引不一致的情况,但也会出现索引不一致的情况,例如:

  • 当用户创建具有unique键约束的索引并且一个分片包含具有重复文档的块时。在这种情况下,创建索引操作可能会在没有重复的分片上成功,但在没有重复的分片上不会成功。

注意

下面的管道用于MongoDB 4.2.4及以上版本。

  1. const pipeline = [
        // Get indexes and the shards that they belong to.
        {$indexStats: {}},
        // Attach a list of all shards which reported indexes to each document from $indexStats.
        {$group: {_id: null, indexDoc: {$push: "$$ROOT"}, allShards: {$addToSet: "$shard"}}},
        // Unwind the generated array back into an array of index documents.
        {$unwind: "$indexDoc"},
        // Group by index name.
        {
            $group: {
                "_id": "$indexDoc.name",
                "shards": {$push: "$indexDoc.shard"},
                // Convert each index specification into an array of its properties
                // that can be compared using set operators.
                "specs": {$push: {$objectToArray: {$ifNull: ["$indexDoc.spec", {}]}}},
                "allShards": {$first: "$allShards"}
            }
        },
        // Compute which indexes are not present on all targeted shards and
        // which index specification properties aren't the same across all shards.
        {
            $project: {
                missingFromShards: {$setDifference: ["$allShards", "$shards"]},
                inconsistentProperties: {
                     $setDifference: [
                         {$reduce: {
                             input: "$specs",
                             initialValue: {$arrayElemAt: ["$specs", 0]},
                             in: {$setUnion: ["$$value", "$$this"]}}},
                         {$reduce: {
                             input: "$specs",
                             initialValue: {$arrayElemAt: ["$specs", 0]},
                             in: {$setIntersection: ["$$value", "$$this"]}}}
                     ]
                 }
            }
        },
        // Only return output that indicates an index was inconsistent, i.e. either a shard was missing
        // an index or a property on at least one shard was not the same on all others.
        {
            $match: {
                $expr:
                    {$or: [
                        {$gt: [{$size: "$missingFromShards"}, 0]},
                        {$gt: [{$size: "$inconsistentProperties"}, 0]},
                    ]
                }
            }
        },
        // Output relevant fields.
        {$project: {_id: 0, indexName: "$$ROOT._id", inconsistentProperties: 1, missingFromShards: 1}}
    ];
  2. 运行要测试的分片集合的聚合管道。例如,要测试分片集合是否测试。在相关的碎片上有不一致的索引:

    db.getSiblingDB("test").reviews.aggregate(pipeline)

    如果集合的索引不一致,则该集合的聚合将返回关于不一致索引的详细信息:

    { "missingFromShards" : [ "shardB" ], "inconsistentProperties" : [ ], "indexName" : "page_1_score_1" }
    { "missingFromShards" : [ ], "inconsistentProperties" : [ { "k" : "expireAfterSeconds", "v" : 60 }, { "k" : "expireAfterSeconds", "v" : 600 } ], "indexName" : "reviewDt_1" }

返回的文档指出了分片集合 test.reviews 的两个不一致之处:

  1. shardB上的集合中缺少一个名为page_1_score_1的索引。

    1. 一个名为reviewDt_1的索引在集合的各个分片上具有不一致的属性,特别是expireAfterSeconds属性不同。

要解决特定分片集合中缺少索引的不一致问题

​ 从受影响的分片上的集合中删除不正确的索引,然后重建索引。要重建索引,您可以:

  • 或者

要解决索引属性在各个分片之间的差异

​ 从受影响的分片上的集合中删除不正确的索引,并重新构建索引。重建索引,你可以:

  • 或者

列出所有索引的类型(例如,)集合在所有数据库,您可以使用以下操作在shell:

要删除一个索引,使用方法。

对于索引,将索引名称传递给 方法。有关详细信息,请参见。

从MongoDB 4.2开始,可以接受一个索引名称数组。

你也可以使用从一个集合中删除之外的所有索引。

这些shell助手提供了的包装器。您的可能有一个不同的或额外的接口用于这些操作。

要修改现有索引,您需要删除并重新创建索引。是该规则的例外 ,可以通过命令与收集标志一起 对其进行修改。

当用户创建一个索引碎片在对面(滚动的方式但是无论未能构建相关碎片或是不正确的索引构建索引与不同的规范。

从MongoDB 4.2.6,主,默认情况下,检查索引不一致在分片的碎片集合,和命令,主要配置服务器上运行时,返回字段来报告索引不一致的分片集合的数量。

如果报告任何索引不一致,则可以对分片集合运行以下管道,直到找到不一致为止。

定义以下:

在受影响的分片上为集合执行。

从一个 实例发出一个索引构建 。该操作仅在没有索引的分片上构建集合的索引。

在受影响的碎片上为集合执行。

从一个 实例发出一个索引构建 。该操作仅在没有索引的碎片上构建集合的索引。

或者,如果不一致是该expireAfterSeconds属性,则可以运行命令以更新秒数,而不是删除并重建索引。

散列
文本
mongo
db.collection.dropIndex()
db.collection.dropIndexes()
db.collection.dropIndex()
文本
db.collection.dropIndex()
使用索引名称删除文本索引
' db.collection.dropIndexes() '
db. collections . dropindexes ()
_id索引
dropIndexes 数据库命令
客户端库
TTL索引
collMod
index
(即手动构建跨多个碎片索引一个接一个地)
配置服务器
("serverStatus")
shardedIndexConsistency
shardedIndexConsistency
聚合管道
滚动索引构建
mongos
db.collection.createIndex()
滚动索引构建
mongos
db.collection.createIndex()
collMod
db. collections . getindexes ()
驱动程序的方法
mongo
查看现有索引
删除索引
修改索引
在分片中查找不一致的索引