On this page
  1. Step 1. Find out how large the MongoDB log directory is.
  2. Step 2. Rotate log files.
  3. Step 3. Remove the old logs.
Hundreds of drawers symbolizing a large amount of occupied space

Flush (Delete or Empty) MongoDB log file

Find out how to flush (delete or empty) the MongoDB log file to improve performance and get more space on the disk.

Sometimes the database might work slowly and one of the reasons is a large log file. Tracking database activity is crucial for performance and issues monitoring. However, the log file may grow and therefore may cause the performance issue because of more and more writing and reading on a larger and larger log file. We may avoid such problems by scheduling regular log rotation and keeping the log file size below a defined threshold. Let’s get started on figuring out how to address this issue.

Step 1. Find out how large the MongoDB log directory is.

All below actions refer to Ubuntu 22.04.

We need to check how large is the log file first. We’ll use the following command:

du -h --max-depth=1 /var/log

The command should display a list of directories along with their size calculation.

List of directories under var/log on Ubuntu 22.04

Now let’s list the content of the /var/log/mongodb:

$ cd /var/log/mongodb
$ ls -al


Step 2. Rotate log files.

MongoDB is a great option for NoSQL, but sometimes we may forget to set some basic maintenance tasks, like managing log files. This leads to the fact that MongoDB logs can grow to tens of gigabytes. To avoid that log rotation should be set. Note that MongoDb does not automatically rotate log files as for official documentation.

What MongoDB says about log rotation:

MongoDB’s standard log rotation approach archives the current log file and starts a new one. To do this, the mongod or mongos instance renames the current log file by appending a UTC timestamp to the filename, in ISODate format. It then opens a new log file, closes the old log file, and sends all new log entries to the new log file.

Let’s then set the log to rotate for MongoDB. This will force a file rotation, mongod process will create another file, and you are able to delete the old one. First step is to open Mongo Shell:

$ mongosh

Once the MongoDB shell opens use the following commands:

> use admin
> db.adminCommand({ logRotate: 1 })


{ ok: 1 }

Step 3. Remove the old logs.

Now, to remove old logs make sure you are still in /var/log/mongodb directory (e.g. using pwd command) and list all files:

$ ls -al

There should be listed two files: 1. mongod.log and 2. mongod.log.date (e.g. mongod.log.2023-02-06T19-35-28). The old logs are in file number 2. Now we can remove this file:

$ rm mongod.log.2023-02-06T19-35-28

And that’s it. Now you should get not only more space on the disk, but also speed up your MongoDB instance.

Related posts

Leave a Reply

SiteLint Audits: Monitoring in real-time Accessibility, Performance, Privacy, Security, SEO, Runtime Errors and Console Logs