Docs Menu
Docs Home
/
MongoDB Manual
/ / /

Unshard a Collection

On this page

  • About this Task
  • Access Control
  • Before you Begin
  • Steps
  • Learn More

You can unshard a sharded collection with the unshardCollection command. When you unshard a collection, the collection cannot be partitioned across multiple shards and the shard key is removed.

By default, when you unshard a collection, MongoDB moves the collection's data to the shard with the least amount of data. Alternatively, you can specify which shard to place the data on.

You can perform this task on deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

Note

This task is not available on the Atlas Shared Tier or on Atlas Serverless.

If your deployment has access control enabled, the enableSharding role grants you access to run the unshardCollection command.

Before you unshard your collection, ensure that you meet the following requirements:

  • Your application can tolerate a period of two seconds where the affected collection blocks writes. During the time period where writes are blocked, your application experiences an increase in latency.

  • Your database meets these resource requirements:

    • Ensure the shard you are moving the collection to has enough storage space for the collection and its indexes. The destination shard requires at least ( Collection storage size + Index Size ) * 2 bytes available.

    • Ensure that your I/O capacity is below 50%.

    • Ensure that your CPU load is below 80%.

1

If you want to put the data from your sharded collection on a specific shard, you need the target shard's name.

To see the list of shard names in your cluster, use the listShards command:

db.adminCommand( { listShards: 1 } )

The shards._id field lists the name of each shard.

2

To unshard a collection, run the unshardCollection command. The following example unshards a collection called us_accounts in the sales database:

db.adminCommand( {
unshardCollection: "sales.us_accounts",
toShard: "shard1"
} )

After the unshard operation completes, the data in the us_accounts collection is on shard1. If you omit the toShard field, the data is placed on the shard with the least amount of data.

3

To confirm that the collection is unsharded, use the $shardedDataDistribution stage and try to match on the unsharded namespace:

db.aggregate( [
{ $shardedDataDistribution: { } },
{ $match: { "ns": "sales.us_accounts" } }
] )

If the aggregation doesn't return any data, the collection is unsharded.

Back

Unsharded Collections