Can I set different database directories in MongoDB? In db2 we can create databases on different directories through db2 list db directory. Can we also do that on MongoDB?

I am aware of the dbPath in the config file. But do all databases created have to be stored there?
All databases for a MongoDB server are created within the configured storage.dbPath directory.

You can't directly specify directory paths for new databases via an end user command, however you can enable the storage.directoryPerDB option in your mongod config to use a separate subdirectory for each database. The subdirectory name used is determined by the storage engine, but the default storage engines (WiredTiger in MongoDB 3.2+, MMAPv1 in earlier versions) currently base this on the database name. Since database names use UTF8, any special characters that might be problematic will be encoded when mapped to a subdirectory name.

With a directoryPerDB  configuration you can also mount or symlink subdirectories to different volumes in your filesystem (assuming the dbPath isn't in use when you change existing mount points). This can be useful if you want to separate I/O for different databases. Note: if you end up managing databases on different volumes this may also affect your backup strategy. For example, filesystem-level backups require a consistent backup of the full dbPath — you cannot independently backup database subdirectories in a MongoDB deployment.

An important caveat noted in the documentation:


  To change the directoryPerDB option for existing deployments, you must restart  mongod instances with the new directoryPerDB value and a new data directory (dbPath), and then repopulate the data.


The directoryPerDB config option can vary per member in a replica set, which can be useful for migration between different dbPath layouts without downtime.