在MongoDB中,数据目录是用于存储数据库文件的地方。默认情况下,MongoDB的数据目录位于/data/db
(Linux/macOS)或C:\data\db
(Windows)。如果你想更改数据目录,可以按照以下步骤操作:
-
停止MongoDB服务。
对于Linux/macOS,使用以下命令:
sudo service mongod stop
或者
sudo systemctl stop mongod
对于Windows,使用以下命令:
net stop MongoDB
-
创建一个新的数据目录。确保MongoDB用户(例如,在Linux上的
mongodb
用户)对新目录具有读写权限。对于Linux/macOS,使用以下命令:
sudo mkdir -p /new/data/directory sudo chown mongodb:mongodb /new/data/directory
对于Windows,使用以下命令:
mkdir C:\new\data\directory icacls C:\new\data\directory /grant MongoDB:(OI)(CI)F
-
使用
mongod
命令的--dbpath
参数启动MongoDB,并指定新的数据目录。在Linux/macOS上,你可以在/etc/init.d/mongod
或/etc/systemd/system/mongod.service
文件中修改DBPath
设置。对于Windows,你可以在C:\Program Files\MongoDB\Server\
文件中修改\mongod.cfg storage.dbPath
设置。例如,对于Linux/macOS,你可以将
/etc/init.d/mongod
或/etc/systemd/system/mongod.service
文件中的DBPath
行更改为:DBPath=/new/data/directory
对于Windows,你可以将
C:\Program Files\MongoDB\Server\
文件中的\mongod.cfg storage.dbPath
行更改为:storage: dbPath: C:\new\data\directory
-
重新启动MongoDB服务。
对于Linux/macOS,使用以下命令:
sudo service mongod start
或者
sudo systemctl start mongod
对于Windows,使用以下命令:
net start MongoDB
现在,MongoDB应该已经在新设置的数据目录中运行。你可以通过查看MongoDB日志文件或使用db.runCommand({ connectionStatus: 1 })
命令来验证数据目录是否已更改。