Starting in MongoDB 7.0.3 (and 6.0.12 and 5.0.22), you can drop the index for a hashed shard key.从MongoDB 7.0.3(以及6.0.12和5.0.22)开始,您可以删除哈希分片键的索引。
This can speed up data insertion for collections sharded with a hashed shard key.这可以加速使用哈希分片键分片的集合的数据插入。
About this Task关于此任务
Dropping an unnecessary index can speed up CRUD operations. Each CRUD operation has to update all the indexes related to a document. Removing one index can increase the speed of all CRUD operations.删除不必要的索引可以加快CRUD操作。每个CRUD操作都必须更新与文档相关的所有索引。删除一个索引可以提高所有CRUD操作的速度。
Important
You should only drop a hashed shard key index from a collection if a supporting non-hashed index on the shard key exists. 只有当分片键上存在支持的非哈希索引时,才应该从集合中删除哈希分片键索引。If a supporting non-hashed index does not exist on the shard key, queries filtering by the shard key perform a collection scan. 如果分片键上不存在支持的非哈希索引,则按分片键筛选的查询将执行集合扫描。To see what indexes exist on a collection, use 要查看集合上存在哪些索引,请使用db.collection.getIndexes().db.collection.getIndexes()。
Considerations注意事项
When dropping a hashed shard key index, consider the following:删除哈希分片键索引时,请考虑以下事项:
The server disables balancing for your collection and excludes the collection from future balancing rounds. To include the collection in future balancing rounds, recreate the shard key index.服务器禁用集合的平衡,并将该集合排除在未来的平衡轮次之外。要在未来的平衡回合中包含该集合,请重新创建分片键索引。When you drop the shard key index, the range deleter does not clean up any remaining orphans in your collection. You must confirm that no orphaned documents exist in your collection before dropping the hashed shard key index. See the below procedure for how to confirm that there are no orphaned documents in your collection.当你删除分片键索引时,范围删除器不会清理集合中任何剩余的孤立项。在删除哈希分片键索引之前,您必须确认集合中不存在孤立文档。请参阅以下过程,了解如何确认集合中没有孤立文档。
Steps步骤
Stop the balancer停止平衡器
Run the following command to stop the balancer:运行以下命令以停止平衡器:
sh.stopBalancer()
You can only run 您只能在sh.stopBalancer() on mongos. sh.stopBalancer() produces an error if run on mongod.mongos上运行sh.stopBalancer()。如果在mongod上运行sh.stopBalancer(),则会产生错误。
Confirm there are no orphaned documents in your collection确认集合中没有孤立文档
Starting in MongoDB 6.0.3, you can run an aggregation using the 从MongoDB 6.0.3开始,您可以使用$shardedDataDistribution stage to confirm no orphaned documents remain:$shardedDataDistribution阶段运行聚合,以确认没有孤立文档残留:
db.aggregate([
{ $shardedDataDistribution: {} },
{ $match: { "ns": "<database>.<collection>" } }
])
$shardedDataDistribution has output similar to the following:输出类似于以下内容:
[
{
"ns": "test.names",
"shards": [
{
"shardName": "shard-1",
"numOrphanedDocs": 0,
"numOwnedDocuments": 6,
"ownedSizeBytes": 366,
"orphanedSizeBytes": 0
},
{
"shardName": "shard-2",
"numOrphanedDocs": 0,
"numOwnedDocuments": 6,
"ownedSizeBytes": 366,
"orphanedSizeBytes": 0
}
]
}
]
Ensure that 确保集群中每个分片的"numOrphanedDocs" is 0 for each shard in the cluster."numOrphanedDocs"为0。