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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With