Drop a Hashed Shard Key Index
On this page
Starting in MongoDB 7.0.3 (and 6.0.12 and 5.0.22), you can drop the index for a hashed shard key.
This can speed up data insertion for collections sharded with a hashed
shard key. It can also speed up data ingestion when using
mongosync
.
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.
When you drop a hashed shard key index, the server disables balancing for that collection and excludes the collection from future balancing rounds. In order to include the collection in balancing rounds once again, you must recreate the shard key index.
Steps
Confirm there are no orphaned documents in your collection
Starting in MongoDB 6.0.3, you can run an aggregation using the
$shardedDataDistribution
stage to confirm no orphaned
documents remain:
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.