Definition
Compatibility
This command is available in deployments hosted in the following environments:
- MongoDB 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.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The command has the following syntax:
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 |
|---|---|---|
| string | The name of the collection. |
| boolean | New in version 8.0. : If enabled, the Default: False |
| boolean | Optional. If enabled, forces |
| Integer | Optional. Specifies the minimum amount of storage space, in megabytes, that must be recoverable for compaction to proceed. Default: 20 |
| 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:
A comment can be any valid BSON type (string, integer, object, array, etc). |
Note
The compact command does not block MongoDB CRUD Operations operations on the database it is compacting.
compact Required Privileges
For clusters enforcing authentication, you must authenticate as a user with the compact privilege action on the target collection. The dbAdmin and hostManager roles provide the required privileges for running compact against non-system collections.
For system collections, you must:
Create a custom role that grants the
compactaction on the system collection.Grant that role to a new or existing user.
Authenticate as that user to perform the
compactcommand.
For example, the following operations create a custom role that grants the compact action against the specified database and collection:
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.
To add the dbAdmin, hostManager, or the custom role to an existing user, use db.grantRolesToUser() or db.updateUser(). The following operation grants the custom compact role to the myCompactUser on the admin database:
use admin db.grantRolesToUser("myCompactUser", [ "dbAdmin" | "myCustomCompactRole" ] )
To add the dbAdmin or the custom role to a new user, specify the role to the roles array of the db.createUser() method when creating the user.
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 log file or run db.currentOp() from another shell instance.
Operation Termination
If you terminate compact with the 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 reduces 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 command before and after compaction. You can use the output metric 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 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. Consider the following:
The primary node does not replicate the
compactcommand to the secondaries.Run
compacton secondary nodes whenever possible. If you cannot runcompacton secondaries, see the force option.Starting in MongoDB 6.1.0 (and 6.0.2):
A secondary node can replicate while
compactis running.Reads are permitted.
To run compact on a cluster:
Reassign the primary node.
To step down the current primary and trigger an election, use the rs.stepDown() method. To nominate a particular secondary node, adjust the member priority.
Version Specific Considerations for Secondary Nodes
A secondary node can replicate while
compactis running.Reads are permitted.
While the compact command is running, the replica set remains in a SECONDARY status.
For more information about replica set member states, see Replica Set Member States.
For replica set maintenance and availability, see Perform Maintenance on Self-Managed Replica Set Members.
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
compacton the affected node.Perform an initial sync of the affected node.
Drop and recreate 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 instances. In a sharded environment, run compact on each shard separately as a maintenance operation.
You cannot issue compact against a 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.
Compact a Collection
The following operation runs the compact command on the movies collection:
db.runCommand( { compact: "movies", force: true } )
{ bytesFreed: "...", ok: 1 }
Estimate Compaction
The following operation performs a dry run of the compact command on the movies collection:
db.runCommand( { compact: "movies", dryRun: true, force: true } )
{ estimatedBytesFreed: "...", ok: 1 }