MongoDB

MongoDB Change Data Directory

When working as a database administrator, you will encounter instances where you need to customize the environment of the database server.

This article will show you how to customize the location where the MongoDB server stores the data files. This is useful when you need to set a custom location for your data files without changing the source code of the MongoDB server.

Now, let’s jump in.

Where Does MongoDB Store its Data Files?

The first thing you should understand before changing the data directory is where MongoDB stores the data files by default.

Keep in mind that the default data directory for the MongoDB server will vary depending on the installation method and the target host system.

However, you can check the MongoDB configuration file to learn more. The following is the default data directory for MongoDB version 6.0 on Windows and Debian:

Windows -> C:\Program Files\MongoDB\Server\6.0\data
Debian -> /var/lib/mongodb

 
Once you have noted down the default location values, we can proceed to learn how to modify the data directory.

Method 1 – Temporarily Change the MongoDB Data Directory

The first method to change the default data directory is during the server startup process. The mongod command provides us with the –dbpath parameter, which allows us to specify a custom data directory for the server.

The command syntax is shown below:

$ mongod --dbpath="path/to/data/directory"

 
The command will start the server setting the data directory as the specified value.

It is good to keep in mind that this is a temporary measure. Once you restart the server, MongoDB will switch back to the default data directory defined in the server configuration file.

Method 2 – Permanently Set the MongoDB Data Directory

If you want to permanently set the default data directory that will persist when you reboot the server, you can make changes to the configuration file.

Locate the mongod.conf file found in the install_dir/bin directory.

$ sudo nano /etc/ mongod.conf

 
Next, locate the entry shown below:

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

 
Change the value of the dpPath parameter to the path of your target data directory.

storage:
  dbPath: /data/db
  journal:
    enabled: true

 
Save the file and restart the MongoDB Server.

NOTE: Ensure your target data directory exists on the system before restarting the server.

Conclusion

This post discussed configuring a custom data directory for the MongoDB server using the-dbpath parameter and the configuration file. Two methods were discussed with the corresponding examples.

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