> This page location: /docs.md > /docs/development.md > /docs/manual/reference/command.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# rewriteCollection (database command)

## Definition

Rewrites a sharded collection to disk using the same shard key.

Use this command to redistribute data when adding or removing shards, or to reclaim disk space.

To stop an in-progress collection rewrite, use the [`abortRewriteCollection`](https://www.mongodb.com/docs/manual/reference/command/abortrewritecollection.md#mongodb-dbcommand-dbcmd.abortRewriteCollection) command.

**New in version 8.3**

## Compatibility

This command is available in deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

**Note:**

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see [Unsupported Commands.](https://www.mongodb.com/docs/atlas/unsupported-commands/)

- [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

The command has the following syntax:

```javascript
db.adminCommand( {
   rewriteCollection: "<database>.<collection>",
   numInitialChunks: <int>,
   zones: <zones>
} )
```

## Command Fields

The command takes the following fields:

| Field | Type | Description |
| --- | --- | --- |
| `rewriteCollection` | string | Required. Name of the database and collection to rewrite. |
| `numInitialChunks` | integer | Optional. Number of initial chunks to use to reshard the collection. It defaults to 90. |
| `zones` | array | Optional. Documents that specify the zones for the shard key. |

## Considerations

Before you begin rewriting 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.

  If your workload cannot tolerate this requirement, consider [refining your shard key](https://www.mongodb.com/docs/manual/core/sharding-refine-a-shard-key.md#std-label-shard-key-refine) instead.

- Your database meets these resource requirements:

  - Ensure that the available storage space on each recipient shard is at least twice the storage size of the collection that you want to rewrite plus its total index size, divided by the number of shards:

    ```none
    ( ( collection_storage_size + index_size ) * 2 ) / shard_count = storage_req
    ```

    For example, consider a collection with a storage size of 2 TB data and a 400 GB index. To distribute it across four shards you'd need:

    ```none
    ( ( 2 TB collection + 0.4 TB index ) * 2 ) / 4 shards = 1.2 TB storage
    ```

    To rewrite this collection, each shard requires 1.2 TB of available storage.

    On MongoDB Atlas, you may need to upgrade to the next tier of storage for the rewrite operation. You can downgrade once the operation completes.

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

  - Ensure that your CPU load is below 80%.

  **Important:**

  These requirements are not enforced by the database. A failure to allocate enough resources can result in:

  - the database running out of space and shutting down

  - decreased performance

  - the operation taking longer than expected

  If your application has time periods with less traffic, perform this operation on the collection during that time if possible.

- You do not need to create an index on the new shard key before resharding. The resharding operation builds the required indexes automatically during the index phase.

- No index builds are in progress. To check for running index builds, use `$currentOp`:

  ```javascript
  db.getSiblingDB("admin").aggregate( [
     { $currentOp : { idleConnections: true } },
     { $match: {
           $or: [
               { "op": "command", "command.createIndexes": { $exists: true } },
               { "op": "none", "msg": /^Index Build/ }
           ]
        }
     }
  ] )
  ```

  In the result document, if the `inprog` field value is an empty array, there are no index builds in progress:

  ```javascript
  {
     inprog: [],
     ok: 1,
     '$clusterTime': { ... },
     operationTime: <timestamp>
  }
  ```

**Note:**

A rewriting operation is a write-intensive process which can generate increased rates of oplog. You may wish to:

- set a fixed oplog size to prevent unbounded oplog growth.

- increase the oplog size to minimize the chance that one or more secondary nodes becomes stale.

See the [Replica Set Oplog](https://www.mongodb.com/docs/manual/core/replica-set-oplog.md#std-label-replica-set-oplog) documentation for more details.

### Rewrite Limitations

- Only one of the following operations can run at a time on the cluster: [`moveCollection`](https://www.mongodb.com/docs/manual/reference/command/movecollection.md#mongodb-dbcommand-dbcmd.moveCollection), [`reshardCollection`](https://www.mongodb.com/docs/manual/reference/command/reshardcollection.md#mongodb-dbcommand-dbcmd.reshardCollection), [`rewriteCollection`](https://www.mongodb.com/docs/manual/reference/command/rewritecollection.md#mongodb-dbcommand-dbcmd.rewriteCollection), and [`unshardCollection`.](https://www.mongodb.com/docs/manual/reference/command/unshardcollection.md#mongodb-dbcommand-dbcmd.unshardCollection)

- If the collection uses [Atlas Search](https://www.mongodb.com/docs/search.md#std-label-atlas-search), the search index becomes unavailable after the operation completes. To restore it, manually rebuild the search index.

- Collections that use queryable encryption are not supported.

## Access Control

The `rewriteCollection` command requires the [`rewriteCollection`](https://www.mongodb.com/docs/manual/reference/privilege-actions.md#mongodb-authaction-rewriteCollection) privilege action on the cluster or on the database and collection you want to rewrite.

This privilege action is also available to users with the following roles:

- [`enableSharding`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-enableSharding)

- [`clusterManager`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-clusterManager)

## Examples

To rewrite a collection, run the following command:

```javascript
db.adminCommand( {
  rewriteCollection: "sales.orders"
} )
```

## Learn More

- [Reshard to the Same Shard Key](https://www.mongodb.com/docs/manual/core/reshard-to-same-key.md#std-label-reshard-to-same-key)

- [Reshard a Collection back to the Same Shard Key](https://www.mongodb.com/docs/manual/tutorial/resharding-back-to-same-key.md#std-label-resharding-a-collection-back-to-same-key)

- [Resharding for Adding and Removing Shards](https://www.mongodb.com/docs/manual/tutorial/resharding-for-adding-and-removing-shards.md#std-label-resharding-for-adding-and-removing-shards-tutorial)

- [`reshardCollection`](https://www.mongodb.com/docs/manual/reference/command/reshardcollection.md#mongodb-dbcommand-dbcmd.reshardCollection)

- [`moveCollection`](https://www.mongodb.com/docs/manual/reference/command/movecollection.md#mongodb-dbcommand-dbcmd.moveCollection)
