In this tutorial, we will explore how to use the compact command in MongoDB. The compact command allows you to rewrite and defragment the data and indexes within a MongoDB collection free up disk space.
Command Syntax
The following code snippet shows the syntax of the compact command:
{
compact:
}
)
The compact command accepts the following parameters:
- <collection_name> – Specifies the name of the collection to compact.
- force – A Boolean parameter that allows the compact command to run on the primary in a given replica set.
- comment – Specifies a comment attached to a given command.
It is good to keep in mind that the compact operation blocks the database on which the compact command is executed. However, it does not affect the other databases in the cluster.
Example:
Let us illustrate how to use the compact command in MongoDB. To best see the effects of the compact command, it is good to view the collection size before compaction.
Suppose that we have a collection called disney which contains the information about Disney movies and tv shows.
We can get the collection disk usage before compaction with the following command:
The previous command returns the statistics about the specified collection. What we are interested in is the collection size. An example output is as shown:
nindexes: 3,
indexBuilds: [],
totalIndexSize: 104,
totalSize: 400,
indexSizes: { _id_: 28, title_1: 52, type_1: 24 },
scaleFactor: 1024,
ok: 1
}
In this case, we can see that the collection takes up 400kb of data before compaction.
Running the Compaction Command
We can run the compaction operation as shown in the following:
The command should return an output as shown in the following:
{ bytesFreed: 300, ok: 1 }
We can then check the usage statistics as follows:
nindexes: 3,
indexBuilds: [],
totalIndexSize: 104,
totalSize: 399,
indexSizes: { _id_: 28, title_1: 52, type_1: 24 },
scaleFactor: 1024,
ok: 1
}
We can see that the command releases 30 bytes of data.
Conclusion
In this short post, we covered how to use the compact command in MongoDB to defragment the data in a given collection and release a disk space to the host system.