On this page本页内容
This page shows how to manage existing indexes. 此页显示如何管理现有索引。For instructions on creating indexes, refer to the specific index type pages.有关创建索引的说明,请参阅特定的索引类型页面。
The following sections provide methods for viewing existing indexes on a collection or an entire database.以下部分提供了查看集合或整个数据库上现有索引的方法。
To view a list of all indexes on a collection in MongoDB Compass, click on the target collection in the left-hand pane and select the Indexes tab.要查看MongoDB Compass中集合上所有索引的列表,请单击左侧窗格中的目标集合并选择“索引”选项卡。
For details on the information displayed in this tab, refer to the Compass documentation.有关此选项卡中显示的信息的详细信息,请参阅Compass文档。
To return a list of all indexes on a collection, use the 要返回集合上所有索引的列表,请使用db.collection.getIndexes()
method or a similar method for your driver.db.collection.getIndexes()
方法或类似的驱动程序方法。
For example, to view all indexes on the 例如,要查看people
collection, run the following command:people
集合上的所有索引,请运行以下命令:
db.people.getIndexes()
To list all the collection indexes in a database, you can use the following operation in 要列出数据库中的所有集合索引,可以在mongosh
:mongosh
中使用以下操作:
db.getCollectionNames().forEach(function(collection) { indexes = db[collection].getIndexes(); print("Indexes for " + collection + ":"); printjson(indexes); });
Starting in version 3.0, MongoDB deprecates direct access to the 从3.0版开始,MongoDB反对直接访问system.indexes
collection, which had previously been used to list all indexes in a database.system.indexes
集合,该集合以前用于列出数据库中的所有索引。
To list all indexes of a certain type (e.g. hashed, text) for all collections in all database, you can use the following operation in 要列出所有数据库中所有集合的特定类型的所有索引(例如mongosh
:hash
、text
),可以在mongosh
中使用以下操作:
// 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 " + d.name + "." + c.name); printjson(idx); }; }); }); });
If you drop an index that is actively used in production, your application may incur a performance degradation. 如果删除生产中正在使用的索引,应用程序可能会导致性能下降。Before you drop an index, you can evaluate the potential impact of the drop by hiding the index.在删除索引之前,可以通过隐藏索引来评估删除的潜在影响。
Hidden indexes are not used to support queries. 隐藏索引不用于支持查询。If you hide an index and observe substantial negative performance impact, consider keeping and unhiding the index so queries can resume using it.如果您隐藏了一个索引,并观察到了显著的负面性能影响,请考虑保留和取消隐藏该索引,以便查询可以继续使用它。
When removing indexes in the MongoDB Shell, you can either:在MongoDB Shell中删除索引时,您可以:
Remove a specific index.删除特定索引。
Remove all indexes from the collection.从集合中删除所有索引。
To remove an index, use the 要删除索引,请使用db.collection.dropIndex()
method.db.collection.dropIndex()
方法。
For example, the following operation removes an ascending index on the 例如,以下操作将删除tax-id
field in the accounts
collection:accounts
集合中tax-id
字段上的升序索引:
db.accounts.dropIndex( { "tax-id": 1 } )
The operation returns a document with the status of the operation:该操作返回一个文档,其中包含该操作的状态:
{ "nIndexesWas" : 3, "ok" : 1 }
Where the value of 其中nIndexesWas
reflects the number of indexes before removing this index.nIndexesWas
的值反映了删除此索引之前的索引数。
For text indexes, pass the index name to the 对于db.collection.dropIndex()
method. text
索引,将索引名称传递给db.collection.dropIndex()
方法。See Use the Index Name to Drop a 有关详细信息,请参阅使用索引名称删除text
Index for details.text
索引。
Starting in MongoDB 4.2, 从MongoDB 4.2开始,db.collection.dropIndexes()
can accept an array of index names.db.collection.dropIndexes()
可以接受索引名称数组。
Starting in MongoDB 4.4, 从MongoDB 4.4开始,db.collection.dropIndexes()
can stop in-progress index builds. db.collection.dropIndexes()
可以停止正在进行的索引构建。See Stop In-Progress Index Builds for more information.有关详细信息,请参阅停止进行中的索引生成。
You can also use the 您还可以使用db.collection.dropIndexes()
to remove all indexes except for the _id index from a collection.db.collection.dropIndexes()
从集合中删除除_id
索引之外的所有索引。
For example, the following command removes all indexes from the 例如,以下命令从accounts
collection:accounts
集合中删除所有索引:
db.accounts.dropIndexes()
These shell helpers provide wrappers around the 这些shell助手为dropIndexes
database command. dropIndexes
数据库命令提供包装。Your client library may have a different or additional interface for these operations.对于这些操作,您的客户端库可能具有不同的或附加的接口。
To remove an index from a collection in MongoDB Compass:要从MongoDB Compass中的集合中删除索引,请执行以下操作:
Navigate to the collection containing the target index.导航到包含目标索引的集合。
Click the Indexes tab.单击“索引”选项卡。
In the Drop column for the target index, click the trash icon.在目标索引的“放置”列中,单击回收站图标。
To modify an existing index in the MongoDB Shell, you need to drop and recreate the index. 要修改MongoDBShell中的现有索引,需要删除并重新创建索引。The exception to this rule is TTL indexes, which can be modified via the 此规则的例外是TTL索引,可以通过collMod
command in conjunction with the index
collection flag.collMod
命令与index
集合标志一起修改。
To modify an existing index in MongoDB Compass, you need to drop and recreate the index.要修改MongoDB Compass中的现有索引,需要删除并重新创建索引。
If you drop an index that is actively used in production, your application may incur a performance degradation. 如果删除生产中正在使用的索引,应用程序可能会导致性能下降。To ensure queries can still use an index during modification, you can create a temporary, redundant index that contains the same fields as the modified index.为了确保查询在修改期间仍然可以使用索引,可以创建一个临时的冗余索引,该索引包含与修改的索引相同的字段。
This example creates a new index and modifies that index to make it unique.此示例创建一个新索引并修改该索引以使其唯一。
url
fieldurl
字段的临时索引Run this command:运行此命令:
db.siteAnalytics.createIndex( { "url": 1, "dummyField": 1 } )
The command returns the name of the index:该命令返回索引的名称:
url_1_dummyField_1
This temporary index lets you safely drop the original 此临时索引允许您安全地删除原始{ "url": 1 }
index without impacting performance.{ "url": 1 }
索引,而不会影响性能。
{ "url": 1 }
index with the unique
propertyunique
属性重新创建{ "url": 1 }
索引Run this command:
db.siteAnalytics.createIndex( { "url": 1 }, { "unique": true } )
The command returns the name of the index:该命令返回索引的名称:
url_1
The 将重新创建url_1
index is recreated and you can drop the temporary index without impacting performance. url_1
索引,您可以在不影响性能的情况下删除临时索引。Queries on the url
field can use the new unique index.url
字段上的查询可以使用新的唯一索引。
To view the indexes on the 要查看siteAnalytics
collection, run this command:siteAnalytics
集合上的索引,请运行以下命令:
db.siteAnalytics.getIndexes()
The command returns these indexes, indicating that the 该命令返回这些索引,表明url_1
index is now unique:url_1
索引现在是唯一的:
[ { v: 2, key: { _id: 1 }, name: '_id_' }, { v: 2, key: { url: 1 }, name: 'url_1', unique: true } ]
A sharded collection has an inconsistent index if the collection does not have the exact same indexes (including the index options) on each shard that contains chunks for the collection. 如果集合在包含集合块的每个分片上没有完全相同的索引(包括索引选项),则分片集合具有不一致的索引。Although inconsistent indexes should not occur during normal operations, inconsistent indexes can occur , such as:尽管在正常操作期间不应出现不一致的索引,但可能会出现不一致索引,例如:
When a user is creating an index with a 当用户使用unique
key constraint and one shard contains a chunk with duplicate documents. unique
键约束创建索引时,一个分片包含一个包含重复文档的块。In such cases, the create index operation may succeed on the shards without duplicates but not on the shard with duplicates.在这种情况下,创建索引操作可能在没有重复项的分片上成功,但在有重复项的分片上失败。
When a user is creating an index across the shards in a rolling manner (i.e. manually building the index one by one across the shards) but either fails to build the index for an associated shard or incorrectly builds an index with different specification.当用户以滚动方式在分片上创建索引时(即,在分片上一个接一个地手动构建索引),但未能为相关分片构建索引,或者使用不同的规范错误地构建索引。
Starting in MongoDB 4.4 (and 4.2.6), the config server primary, by default, checks for index inconsistencies across the shards for sharded collections, and the command 从MongoDB 4.4(和4.2.6)开始,默认情况下,配置服务器 primary会检查分片集合中的索引不一致,而在配置服务器primary上运行的命令serverStatus
, when run on the config server primary, returns the field shardedIndexConsistency
field to report on the number of sharded collections with index inconsistencies.serverStatus
会返回字段shardedIndexConsistency
,以报告索引不一致的分片集合数。
If 如果shardedIndexConsistency
reports any index inconsistencies, you can run the following pipeline for your sharded collections until you find the inconsistencies.shardedIndexConsistency
报告了任何索引不一致,您可以为分片集合运行以下管道,直到找到不一致。
The following pipeline is for MongoDB 4.2.4 and above.以下管道适用于MongoDB 4.2.4及以上版本。
Define the following aggregation pipeline:定义以下聚合管道:
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}} ];
Run the aggregation pipeline for the sharded collection to test. 运行要测试的分片集合的聚合管道。For example, to test if the sharded collection 例如,要测试分片集合test.reviews
has inconsistent indexes across its associated shards:test.reviews
是否在其关联的分片上具有不一致的索引:
db.getSiblingDB("test").reviews.aggregate(pipeline)
If the collection has inconsistent indexes, the aggregation for that collection returns details regarding the inconsistent indexes:如果集合具有不一致的索引,则该集合的聚合将返回有关不一致索引的详细信息:
{ "missingFromShards" : [ "shardB" ], "inconsistentProperties" : [ ], "indexName" : "page_1_score_1" } { "missingFromShards" : [ ], "inconsistentProperties" : [ { "k" : "expireAfterSeconds", "v" : 60 }, { "k" : "expireAfterSeconds", "v" : 600 } ], "indexName" : "reviewDt_1" }
The returned documents indicate two inconsistencies for the sharded collection 返回的文档表明分片集合test.reviews
:test.reviews
有两个不一致之处:
An index named page_1_score_1
is missing from the collection on shardB
.shardB
上的集合中缺少名为page_1_score_1
的索引。
An index named 名为reviewDt_1
has inconsistent properties across the collection's shards, specifically, the expireAfterSeconds
properties differ.reviewDt_1
的索引在集合的分片中具有不一致的属性,具体而言,expireAfterSeconds
属性不同。
You can either:您可以:
Perform a rolling index build for the collection on the affected shard(s).对受影响的分片上的集合执行滚动索引构建。
-OR-
Issue an index build 从db.collection.createIndex()
from a mongos
instance. mongos
实例发出索引构建。The operation only builds the collection's index on the shard(s) missing the index.该操作仅在缺少索引的分片上构建集合的索引。
Drop the incorrect index from the collection on the affected shard(s) and rebuild the index. 从受影响的分片上的集合中删除不正确的索引并重新生成索引。To rebuild the index, you can either:要重建索引,您可以:
Perform a rolling index build for the collection on the affected shard.对受影响的分片上的集合执行滚动索引构建。
-OR-
Issue an index build 从db.collection.createIndex()
from a mongos
instance. mongos
实例发出索引构建db.collection.createIndex()
。The operation only builds the collection's index on the shard(s) missing the index.该操作仅在缺少索引的分片上构建集合的索引。
Alternatively, if the inconsistency is the 或者,如果不一致性是expireAfterSeconds
property, you can run the collMod
command to update the number of seconds instead of dropping and rebuilding the index.expireAfterSeconds
属性,则可以运行collMod
命令来更新秒数,而不是删除和重建索引。