Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mongodb

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?

like image 368
Carlos Granados Avatar asked Nov 11 '19 11:11

Carlos Granados


1 Answers

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);
like image 168
Rajat Arora Avatar answered Nov 07 '22 10:11

Rajat Arora