简体   繁体   中英

How to copy MongoDB databases using PHP now that copydb is deprecated

In MongoDB version 4.2 copydb and its copyDatabase wrapper have been deprecated. The MongoDB manual suggests that we should now use mongodump and mongorestore . But I was calling the copy command from PHP using the PHP MongoDB driver and the dump and restore commands are commands that need to be run from the command line and don't have any PHP equivalent. How can I now copy a database using PHP?

You can use "mongodump" and "mongorestore" as you mentioned as well. In PHP, you can use shell_exec to run the commands. For example:

$backUpCommand = "mongodump --archive='/tmp/mongodump-dev-db' --db=dev";
shell_exec($backUpCommand);

$restoreCommand = "mongorestore --archive='/tmp/mongodump-dev-db' --db=test --nsFrom='test.*' --nsTo='examples.*'";
shell_exec($restoreCommand);

Please note nsFrom and nsTo are to rename the namespace if you need it. See more details here .

In case you want to copy the dump to another host, try combining --host params of mongorestore. So, in that case, your restore command would be:

$restoreCommand = "mongorestore --host=mongodb1.example.net --port=27017 --username=user --password=$PSWD --authenticationDatabase=admin --archive='/tmp/mongodump-dev-db' --db=test";
shell_exec($restoreCommand);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM