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

# autoCompact (database command)

## Definition

**New in version 8.0**

Enables or disables background [compaction](https://www.mongodb.com/docs/manual/reference/privilege-actions.md#mongodb-authaction-compact). When enabled, `autoCompact` periodically iterates through all available files and continuously runs compaction if there is enough free storage space available.

Before you enable `autoCompact`, run the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#mongodb-pipeline-pipe.-collStats) aggregation stage with the `storageStats: {}` option to see if you have enough available storage space for compaction to proceed. If the amount of available space returned by `freeStorageSize` is less than `freeSpaceTargetMB`, background compaction has no effect.

## Syntax

The command has the following syntax:

```javascript
db.runCommand(
   {
     autoCompact: <boolean>,
     freeSpaceTargetMB: <int>, // Optional
     runOnce: <boolean>, // Optional
   }
)
```

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

## Command Fields

The command can take the following optional fields:

| Field | Type | Description |
| --- | --- | --- |
| `freeSpaceTargetMB` | Integer | Optional. Specifies the minimum amount of storage space, in megabytes, that must be recoverable for compaction to proceed. *Default:* 20 |
| `runOnce` | boolean | Optional. If `runOnce` is set to `true`, background compaction runs only once through every collection on the node. If `runOnce` is set to `false`, background compaction runs continuously on all collections in the database. If a collection fails to compact while `runOnce` is `false`, MongoDB temporarily skips that collection and continues compacting the remaining collections. MongoDB attempts to compact the failed collection again after approximately one hour. |

## Required Privileges

For clusters enforcing [authentication:](https://www.mongodb.com/docs/manual/core/authentication.md#std-label-authentication)

- **MongoDB Atlas:** Users must have the [`autoCompact`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-atlasrole-autoCompact) built-in role.

- **Self-managed deployments:** Users must have the [`compact`](https://www.mongodb.com/docs/manual/reference/privilege-actions.md#mongodb-authaction-compact) privilege action on the cluster. The [`hostManager`](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-hostManager) role provides the required privileges for running `autoCompact`.

## Behavior

### Blocking

Background compaction triggered by `autoCompact` applies the same blocking behavior as the [`compact`](https://www.mongodb.com/docs/manual/reference/command/compact.md#mongodb-dbcommand-dbcmd.compact) command. Consequently, if you call `autoCompact` while background compaction is active, MongoDB returns an error.

If you need to restart `autoCompact` or run it again with different options, you must first stop the current background compaction operation:

```javascript
db.runCommand( { autoCompact: false } )
```

Once the current background compaction is disabled, you can restart `autoCompact` with the new configuration.

### mongod Restarts

When the `mongod` instance restarts, the [`enableAutoCompaction`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.enableAutoCompaction) parameter dictates automatic background compaction. This parameter is disabled by default.

To resume background compaction after the `mongod` restarts, you must re-enable `autoCompact`. To ensure background compaction runs continuously, monitor the `mongod` status and run the `autoCompact` command as needed. Alternatively, you can start the `mongod` instance with the [`--setParameter`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--setParameter) flag and set `enableAutoCompaction` to `true`.

### Excluded Collections

If an [oplog](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-oplog) exists, MongoDB excludes it from background compaction.

### Performance Considerations

We recommend running `autoCompact` during periods of low traffic.

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.

### Replica Sets

You can run background compaction on collections and indexes that are stored in a replica set. However, note the following considerations:

- The primary node does not replicate the `autoCompact` command to the secondary nodes.

- A secondary node can replicate data while background compaction is running.

- Reads and writes are permitted while background compaction is running.

### Sharded Clusters

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

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

## Learn More

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