compact
Definition
compact
- Rewrites and defragments all data and indexes in a collection. OnWiredTiger databases, this command will releaseunneeded disk space to the operating system.
compact
has the following form:
- { compact: <collection name> }
compact
takes the following fields:
Starting in MongoDB 4.2
MongoDB removes the MMAPv1 storage engine and the MMAPv1 specificoptions paddingFactor
, paddingBytes
, preservePadding
for compact
.
FieldTypeDescriptioncompact
stringThe name of the collection.force
booleanOptional. If true
, compact
can run on theprimary in a replica set. If false
,compact
returns an error when run on aprimary, because the command blocks all other operations.
compact
blocks operations only for the databaseit is compacting.
Warning
Always have an up-to-date backup before performing servermaintenance such as the compact
operation.
compact Required Privileges
For clusters enforcing authentication,you must authenticate as a user with the compact
privilegeaction on the target collection. The dbAdmin
role providesthe required privileges for running compact
againstnon-system collections.
For system collections, create acustom role that grants the compact
action on the systemcollection. You can then grant that role to a new or existing user andauthenticate as that user to perform the compact
command.For example, the following operations create a custom role that grantsthe compact
action against specified database andcollection:
- 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.
To add the dbAdmin
or the custom role to an existinguser, use db.grantRoleToUser
or db.updateUser()
.The following operation grants the custom compact
role to themyCompactUser
on the admin
database:
- use admin
- db.grantRoleToUser("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"
- ]
- }
- )
Behavior
Blocking
compact
only blocks operations for the database it is currentlyoperating on. Only use compact
during scheduled maintenanceperiods.
You may view the intermediate progress either by viewing themongod
log file or by running the db.currentOp()
in another shell instance.
Operation Termination
If you terminate the operation with the db.killOp()
method or restart the server before thecompact
operation has finished, be aware of the following:
- If you have journaling enabled, the data remains valid andusable, regardless of the state of the
compact
operation.You may have to manually rebuild the indexes. - If you do not have journaling enabled and the
mongod
orcompact
terminates during the operation, it is impossibleto guarantee that the data is in a valid state. - In either case, much of the existing free space in the collection maybecome un-reusable. In this scenario, you should rerun the compactionto completion to restore the use of this free space.
Disk Space
To see how the storage space changes for the collection, run thecollStats
command before and after compaction.
On WiredTiger, compact
attempts toreduce the required storage space for data and indexes in a collection, releasingunneeded disk space to the operating system. The effectiveness of this operationis workload dependent and no disk space may be recovered. This command is usefulif you have removed a large amount of data from the collection, and do not planto replace it.
compact
may require additional disk space to run on WiredTiger databases.
Replica Sets
compact
commands do not replicate to secondaries in areplica set.
- Compact each member separately.
- Ideally run
compact
on a secondary. See optionforce:true
above for information regarding compacting the primary.
- On secondaries, the
compact
command forces the secondary toenterRECOVERING
state. Read operations issued to aninstance in theRECOVERING
state will fail. Thisprevents clients from reading during the operation. When theoperation completes, the secondary returnstoSECONDARY
state. - See Replica Set Member States for more information aboutreplica set member states.
See Perform Maintenance on Replica Set Members for anexample replica set maintenance procedure to maximize availabilityduring maintenance operations.
Sharded Clusters
compact
only applies to mongod
instances. In asharded environment, run compact
on each shard separatelyas a maintenance operation.
You cannot issue compact
against a mongos
instance.
Capped Collections
On WiredTiger, the compact
command will attempt to compact the collection.
Index Building
New in version 2.6.
mongod
rebuilds all indexes in parallel following thecompact
operation.