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

# compact (database command)

## Definition

Attempts to release unneeded disk space to the operating system.

## 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

**Important:**

This command is not supported in M0 and Flex clusters. For more information, 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.runCommand(
   {
     compact: <string>,
     dryRun: <boolean>,
     force: <boolean>, // Optional
     freeSpaceTargetMB: <int>, // Optional
     comment: <any>, // Optional
   }
)
```

## Command Fields

The command takes the following fields:

| Field | Type | Description |
| --- | --- | --- |
| `compact` | string | The name of the collection. |
| `dryRun` | boolean | **New in version 8.0** If enabled, the `compact` command returns an estimate of how much space, in bytes, compaction can reclaim from the targeted collection. If you run `compact` with `dryRun` set to `true`, MongoDB only returns the estimated value and does not perform any kind of compaction. *Default:* False |
| `force` | boolean | Optional. If enabled, forces `compact` to run on the [primary](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-primary) in a [replica set.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-replica-set) |
| `freeSpaceTargetMB` | Integer | Optional. Specifies the minimum amount of storage space, in megabytes, that must be recoverable for compaction to proceed. *Default:* 20 |
| `comment` | any | Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations: [mongod log messages](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-ref), in the `attr.command.cursor.comment` field.; [Database profiler](https://www.mongodb.com/docs/manual/reference/database-profiler.md#std-label-profiler) output, in the [`command.comment`](https://www.mongodb.com/docs/manual/reference/database-profiler.md#mongodb-data-system.profile.command) field.; [`currentOp`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-dbcommand-dbcmd.currentOp) output, in the [`command.comment`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-data-currentOp.command) field. A comment can be any valid [BSON type](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-bson-types) (string, integer, object, array, etc). |

**Note:**

The `compact` command does not block [MongoDB CRUD Operations](https://www.mongodb.com/docs/manual/crud.md#std-label-crud) operations on the database it is compacting.

## `compact` Required Privileges

For clusters enforcing [authentication](https://www.mongodb.com/docs/manual/core/authentication.md#std-label-authentication), you must authenticate as a user with the [`compact`](https://www.mongodb.com/docs/manual/reference/privilege-actions.md#mongodb-authaction-compact) privilege action on the target collection. The [`dbAdmin`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-dbAdmin) and [`hostManager`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-hostManager) roles provide the required privileges for running `compact` against non-system collections.

For [system collections](https://www.mongodb.com/docs/manual/reference/system-collections.md#std-label-metadata-system-collections), you must:

1. Create a custom role that grants the `compact` action on the system collection.

2. Grant that role to a new or existing user.

3. Authenticate as that user to perform the `compact` command.

For example, the following operations create a custom role that grants the `compact` action against the specified database and collection:

```javascript
use admin
db.createRole(
  {
    role: "myCustomCompactRole",
    privileges: [
      {
        resource: { "db" : "<database>" , "collection" : "<collection>" },
        actions: [ "compact" ]
      }
    ],
    roles: []
  }
)
```

For more information on configuring the `resource` document, see [Resource Document on Self-Managed Deployments.](https://www.mongodb.com/docs/manual/reference/resource-document.md#std-label-resource-document)

To add the [`dbAdmin`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-dbAdmin), [`hostManager`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-hostManager), or the custom role to an existing user, use [`db.grantRolesToUser()`](https://www.mongodb.com/docs/manual/reference/method/db.grantrolestouser.md#mongodb-method-db.grantRolesToUser) or [`db.updateUser()`](https://www.mongodb.com/docs/manual/reference/method/db.updateuser.md#mongodb-method-db.updateUser). The following operation grants the custom `compact` role to the `myCompactUser` on the `admin` database:

```javascript
use admin
db.grantRolesToUser("myCompactUser", [ "dbAdmin" | "myCustomCompactRole" ] )
```

To add the [`dbAdmin`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-dbAdmin) or the custom role to a new user, specify the role to the `roles` array of the [`db.createUser()`](https://www.mongodb.com/docs/manual/reference/method/db.createuser.md#mongodb-method-db.createUser) method when creating the user.

```javascript
use admin
db.createUser(
  {
     user: "myCompactUser",
     pwd: "myCompactUserPassword",
     roles: [
       { role: "dbAdmin", db: "<database>" } | "myCustomCompactRole"
     ]
   }
)
```

## Behavior

### Monitoring Progress

To check the `compact` operation's progress, monitor the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) log file or run [`db.currentOp()`](https://www.mongodb.com/docs/manual/reference/method/db.currentop.md#mongodb-method-db.currentOp) from another shell instance.

### Operation Termination

If you terminate `compact` with the [`db.killOp()`](https://www.mongodb.com/docs/manual/reference/method/db.killop.md#mongodb-method-db.killOp) method or restart the server before the operation finishes, `compact` ends. The operation may not release disk space back to the operating system.

### Disk Space

The `compact` command attempts to reduce disk space for data and indexes in a collection by releasing obsolete blocks to the operating system. Effectiveness depends on how many blocks are available to release and their location in the data file.

To see how the storage space changes for the collection, run the [`collStats`](https://www.mongodb.com/docs/manual/reference/command/collstats.md#mongodb-dbcommand-dbcmd.collStats) command before and after compaction. You can use the output metric [`collStats.freeStorageSize`](https://www.mongodb.com/docs/manual/reference/command/collstats.md#mongodb-data-collStats.freeStorageSize) to view the amount of storage available for reuse.

The operation is iterative, working on segments of the data file in each pass. To estimate how much space `compact` releases, use the `dryRun` flag. Calling `compact` on a collection compacts both the collection and its associated indexes.

`compact` may require additional disk space to run.

### Backups

Compaction regularly checkpoints the database, which can lead to synchronization overhead. On high-traffic databases, this can potentially delay or prevent operational tasks such as taking backups. To avoid unexpected disruptions, disable compaction before taking a backup.

#### Multi-Shard Transactions

**Note:**

If your deployment uses secondary reads and multi-shard transactions, consider running an [initial sync](https://www.mongodb.com/docs/manual/core/replica-set-sync.md#std-label-replica-set-initial-sync) instead of `compact`.

When `compact` runs, WiredTiger temporarily adjusts its block-manager strategy to accommodate the compact workload. The adjustment can slow checkpoint operations and increase the time a member takes to commit a transaction. Delayed transaction commits can cause significant read latency, replication lag, and operational queuing.

### Replica Sets

You can use `compact` on collections and indexes in a replica set; however, consider the following:

- The primary node does not replicate the `compact` command to the secondaries.

- Run `compact` on secondary nodes whenever possible. If you cannot run `compact` on secondaries, see the [force](https://www.mongodb.com/docs/manual/reference/command/compact.md#std-label-compact-force-option) option.

- Starting in MongoDB 6.1.0 (and 6.0.2):

  - A secondary node can replicate while `compact` is running.

  - Reads are permitted.

To run `compact` on a self-managed cluster:

1. Compact the secondary nodes.

   Run `compact` on one of the secondary nodes. When `compact` finishes, repeat the operation on each of the remaining secondaries in turn.

2. Reassign the primary node.

   To step down the current primary and trigger an election, use the [`rs.stepDown()`](https://www.mongodb.com/docs/manual/reference/method/rs.stepdown.md#mongodb-method-rs.stepDown) method. To nominate a particular secondary node, [adjust the member priority.](https://www.mongodb.com/docs/manual/tutorial/adjust-replica-set-member-priority.md#std-label-replica-set-adjust-priority)

3. Compact the old primary.

   After stepping down, the old primary node becomes a secondary node. Run `compact` on the old primary node.

#### Considerations for MongoDB Atlas Clusters

MongoDB Atlas does not support the [`rs.stepDown()`](https://www.mongodb.com/docs/manual/reference/method/rs.stepdown.md#mongodb-method-rs.stepDown) method or changes to member priority, so you cannot reassign the primary node as you do in the self-managed `compact` procedure. Instead, on MongoDB Atlas, run `compact` on each node. To run `compact` on the current primary node, use the [force](https://www.mongodb.com/docs/manual/reference/command/compact.md#std-label-compact-force-option) option. To learn about the performance impact of running `compact` on a node that serves reads and writes, see [Multi-Shard Transactions.](https://www.mongodb.com/docs/manual/reference/command/compact.md#std-label-compact-multi-shard-transactions)

To reclaim disk space without running `compact` on each node, consider running the [`autoCompact`](https://www.mongodb.com/docs/manual/reference/command/autocompact.md#mongodb-dbcommand-dbcmd.autoCompact) command, which continuously runs compaction in the background. Run `compact` directly when you need to compact a specific collection.

#### Version Specific Considerations for Secondary Nodes

- A secondary node can replicate while `compact` is running.

- Reads are permitted.

While the `compact` command is running, the replica set remains in a [`SECONDARY`](https://www.mongodb.com/docs/manual/reference/replica-states.md#mongodb-replstate-replstate.SECONDARY) status.

For more information about replica set member states, see [Replica Set Member States.](https://www.mongodb.com/docs/manual/reference/replica-states.md#std-label-replica-set-member-states)

For replica set maintenance and availability, see [Perform Maintenance on Self-Managed Replica Set Members.](https://www.mongodb.com/docs/manual/tutorial/perform-maintenance-on-replica-set-members.md#std-label-perform-maint-on-replica-set)

### Index Size Differences Across Members

Each node applies writes to its indexes independently. Index storage size can differ across the members of a replica set, even when the members hold identical data. A primary node applies writes directly from client operations. A secondary node applies the same writes from the oplog, often in different batches and order. These write pattern differences change how the storage engine packs and compresses index pages. As a result, an index on one member can grow larger on disk than the same index on another member.

To bring an affected index back in line with the same index on other members, use one of the following remediation options:

- Run `compact` on the affected node.

- Perform an [initial sync](https://www.mongodb.com/docs/manual/core/replica-set-sync.md#std-label-replica-set-initial-sync) of the affected node.

- [Drop and recreate](https://www.mongodb.com/docs/manual/tutorial/manage-indexes.md#std-label-manage-indexes-modify) the affected index.

When you plan storage capacity for a replica set, account for this variation in index size across members.

### Sharded Clusters

`compact` only applies to [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instances. In a sharded environment, run `compact` on each shard separately as a maintenance operation.

You cannot issue `compact` against a [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instance.

### Concurrent Compact Commands Not Allowed

If you try to run multiple concurrent `compact` commands on the same collection, MongoDB returns an error.

## Example

**Note:**

The following examples include `force: true`, which is required when running `compact` against an active replica set primary. To run `compact` without `force: true`, step down the primary first. For more information, see [Replica Sets.](https://www.mongodb.com/docs/manual/reference/command/compact.md#std-label-compact-cmd-replica-sets)

### Compact a Collection

The following operation runs the `compact` command on the `movies` collection:

```javascript
db.runCommand( { compact: "movies", force: true } )

```

**Output:**

```javascript
{ bytesFreed: "...", ok: 1 }

```

### Estimate Compaction

The following operation performs a dry run of the `compact` command on the `movies` collection:

```javascript
db.runCommand( {
   compact: "movies",
   dryRun: true,
   force: true
} )

```

**Output:**

```javascript
{ estimatedBytesFreed: "...", ok: 1 }

```

## Learn More

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