Dumping a MongoDB database is done using the “mongodump” utility in the command prompt. This dump creates a binary export of the database. This export can be restored using the “mongorestore” utility.
A basic dump of a local MongoDB database can be code as follows:
mongodump --db mymongodatabase
To dump a specific collection, simply specify the collection:
mongodump --collection collection --db mymongodatabase
Also, you can dump the database to a specific server location:
mongodump --db mymongodatabase --dbpath /var/mypath/mongodumps
We wanted to create a utility that would allow our client to backup their WordPress-integrated MongoDB database using an admin utility. To do this, we built a PHP class that allows us to enter the database name, the dump location, and go. This tool also ZIPs the binary files for us, allowing us to conserve disk space and contain each dump in one file. You can access this class here: https://github.com/KerryRitter/MongoDumper
A basic usage of this class is done as follows:
$dumper = new MongoDumper("/var/mypath/mongodumps");
$dumper->run("mydb", true); // 'true' shows debug info
This will dump the local ‘mydb’ database to /var/mypath/mongodumps/mydb_[timestamp].zip and display the shell output and various debug info. To remove the debug info, remove the “true” parameter in the “run” function call.
To restore, unzip the BSON and JSON files and upload to a folder on the server with the name of the database you wish to restore to. For example, if you wish to restore “mydatabase”, you will need to put the files in a path such as /var/mypath/mongodumps/mydatabase. To restore the database, use the following command in your command prompt:
There are a number of options available for restoration that you can find in the documentation: http://docs.mongodb.org/manual/tutorial/backup-with-mongodump/
Please note that the published MongoDumper class is the simple core; there are security concerns with using shell_exec that need to be addressed before you use it on a publicly accessible site. If there is an error given by the dump or the dump did not work, make sure to check the MongoDumper.php file and the backup folder’s permissions.