New in version 2.0.
The compact command rewrites and defragments a single collection. Additionally, the command drops all indexes at the beginning of compaction and rebuilds the indexes at the end. compact is conceptually similar to repairDatabase, but works on a single collection rather than an entire database.
The command has the following syntax:
{ compact: <collection name> }
You may also specify the following options:
| Parameters: |
|
|---|
Warning
Always have an up-to-date backup before performing server maintenance such as the compact operation.
Note the following behaviors:
compact blocks all other activity. In MongoDB 2.2, compact blocks activities only for its database. You may view the intermediate progress either by viewing the mongod log file, or by running the db.currentOp() in another shell instance.
compact compacts existing documents in the collection. However, unlike repairDatabase, compact does not reset paddingFactor statistics for the collection. MongoDB will use the existing paddingFactor when allocating new records for documents in this collection.
compact generally uses less disk space than repairDatabase and is faster. However, the compact command is still slow and blocks other database use. Only use compact during scheduled maintenance periods.
If you terminate the operation with the db.killOp() method or restart the server before the compact operation has finished:
compact may increase the total size and number of your data files, especially when run for the first time. However, this will not increase the total collection storage space since storage size is the amount of data allocated within the database files, and not the size/number of the files on the file system.
compact requires a small amount of additional disk space while running but unlike repairDatabase it does not free space on the file system.
You may also wish to run the collStats command before and after compaction to see how the storage space changes for the collection.
compact commands do not replicate to secondaries in a replica set:
Warning
If you run compact on a secondary, the secondary will enter a RECOVERING state to prevent clients from sending read operations during compaction. Once the operation finishes the secondary will automatically return to SECONDARY state. See state for more information about replica set member states. Refer to the “partial script for automating step down and compaction” for an example of this procedure.
compact is a command issued to a mongod. In a sharded environment, run compact on each shard separately as a maintenance operation.
Important
You cannot issue compact against a mongos instance.
It is not possible to compact capped collections because they don’t have padding, and documents cannot grow in these collections. However, the documents of a capped collection are not subject to fragmentation.
See also