Skip to content

Instantly share code, notes, and snippets.

@tuefekci
Last active November 30, 2018 04:31
Show Gist options
  • Select an option

  • Save tuefekci/155e4268831c41748f83d413d3889488 to your computer and use it in GitHub Desktop.

Select an option

Save tuefekci/155e4268831c41748f83d413d3889488 to your computer and use it in GitHub Desktop.
mongodb php backup
/**
*
* @copyright Copyright (c) 2018. Giacomo Tüfekci (https://www.tuefekci.de)
* @github https://github.com/tuefekci
* @license https://www.tuefekci.de/LICENSE.md
*
*/
// IMPORTANT: $this->filesystem needs to be adapted to use case! Also this is not intended for Production Use!
// TODO: For productive use add Exception handling etc. depended on use case.
$mongo = new MongoDB\Client(.....);
// Compress Context
$deflateContext = deflate_init(ZLIB_ENCODING_GZIP, ['level' => 9]);
foreach ($mongo->listDatabases() as $databaseInfo) {
// Todo: should probably checked for collection as well.
if($databaseInfo['empty']) {
continue;
}
$databaseName = (string )$databaseInfo['name'];
foreach ($mongo->$databaseName->listCollections() as $collectionInfo) {
$collectionName = (string )$collectionInfo['name'];
// Get Data
$data = $mongo->$databaseName->$collectionName->find();
// Compress Data
$dump = deflate_add($deflateContext, (string)json_encode(iterator_to_array($data)), \ZLIB_FINISH);
// INFO: for decompress use gzdecode($dump);
$this->filesystem->put('backup/'.date("Y-m-d").'/'.$databaseName."/".$collectionName.'_'.date("H:i:s").'.gtbm', $dump, ['visibility' => 'private']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment