compact (original) (raw)
compact
Attempts to release unneeded disk space to the operating system.
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, M2, M5, 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
The command has the following syntax:
db.runCommand(
{
compact: <string>,
dryRun: <boolean>,
force: <boolean>, // Optional
freeSpaceTargetMB: <int>, // Optional
comment: <any>, // Optional
}
)
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 runcompact with dryRun set to true, MongoDB only returns the estimated value and does not perform any kind of compaction.Default: False |
force | boolean | Changed in version 4.4.Optional. If enabled, forces compact to run on the primary in a replica set. compact does not block MongoDB CRUD Operations on the database it is compacting. |
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, in theattr.command.cursor.comment field.Database profiler output, in the command.comment field.currentOp output, in the command.comment field.A comment can be any valid BSON type(string, integer, object, array, etc). |
For clusters enforcing authentication, you must authenticate as a user with the compact privilege action on the target collection. The dbAdmin andhostManager roles provide the required privileges for runningcompact
against non-system collections.
For system collections, you must:
- Create a custom role that grants the
compact
action on the system collection. - Grant that role to a new or existing user.
- 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:
use admin
db.createRole(
{
role: "myCustomCompactRole",
privileges: [
{
resource: { "db" : "<database>" , "collection" : "<collection>" },
actions: [ "compact" ]
}
],
roles: []
}
)
For more information on configuring the resource
document, seeResource 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 themyCompactUser
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 thedb.createUser() method when creating the user.
use admin
db.createUser(
{
user: "myCompactUser",
pwd: "myCompactUserPassword",
roles: [
{ role: "dbAdmin", db: "<database>" } | "myCustomCompactRole"
]
}
)
To check the compact
operation's progress, monitor themongod log file or run db.currentOp()from another shell instance.
If you terminate compact
with the db.killOp() method or restart the server before the operation finishes, compact
ends and may fail its attempt to release disk space back to the operating system.
The compact
command attempts to reduce the disk space consumed for data and indexes in a collection by releasing obsolete blocks back to the operating system. The effectiveness of compact
is relative to how many blocks are available to be released and where in the data file the blocks are.
To see how the storage space changes for the collection, run thecollStats 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 and operates on segments of the data file in each pass. To view an estimate of how much space compact
will release, use the dryRun
flag. Calling compact
on a collection will compact both the collection and its associated indexes.
compact
may require additional disk space to run.
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.
You can use compact
on collections and indexes that are stored in a replica set, however there are some important considerations:
- The primary node does not replicate the
compact
command to the secondaries. - You should run
compact
on secondary nodes whenever possible. If you cannot runcompact
on secondaries, see the force option. - Starting in MongoDB 6.1.0 (and 6.0.2 and 5.0.12):
- A secondary node can replicate while
compact
is running. - Reads are permitted.
- A secondary node can replicate while
To run compact
on a cluster
Run compact
on one of the secondary nodes. When compact
finishes, repeat the operation on each of the remaining secondaries in turn.
After stepping down, the old primary node becomes a secondary node. Run compact
on the old primary node.
- A secondary node can replicate while
compact
is running. - Reads are permitted.
While the compact
command is running, the replica set remains in aSECONDARY status.
For more information about replica set member states, see See Replica Set Member States.
For replica set maintenance and availability, seePerform Maintenance on Self-Managed Replica Set Members.
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.
mongod rebuilds all indexes in parallel following thecompact
operation.
If you try to run multiple concurrent compact
commands on the same collection, MongoDB returns an error.
The following operation runs the compact
command on themovies
collection:
db.runCommand( { compact: "movies" } )
{ bytesFreed: 27859, ok: 1 }
The following operation performs a dry run of the compact
command on themovies
collection:
db.runCommand( {
compact: "movies",
dryRun: true
} )
{ estimatedBytesFreed: 27859, ok: 1 }