Database Manual / Sharding / Administration / Unsharded Collections

Unshard a Collection

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.

About this Task

Compatibility兼容性

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

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This task is not available on the MongoDB Atlas Free or Flex Tiers.

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Restrictions限制

Access Control

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

Before you Begin开始之前

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%.

Steps步骤

1

(Optional) List shard names

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

Unshard the collection

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

Confirm that the collection is unsharded

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.

Learn More了解更多