MongoDB

MongoDB Compact Collections

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:

db.runCommand(
  {
    compact:
  }
)

The compact command accepts the following parameters:

  1. <collection_name> – Specifies the name of the collection to compact.
  2. force – A Boolean parameter that allows the compact command to run on the primary in a given replica set.
  3. 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:

cinema> db.disney.stats({scale: 1024})

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:

cinema> db.runCommand({compact: "disney", force: true})

The command should return an output as shown in the following:

cinema> db.runCommand({compact: "disney", force: true})
{ 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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list