zot24
9/30/2014 - 2:33 PM

Low level helper class to export your mongo collections or specific documents using DB Reference

Low level helper class to export your mongo collections or specific documents using DB Reference

class MongoExportHelper {
    private $path = './';
    private $database = 'default';

    public function setPath($path) {
        $this->path = $path;
    }

    public function setDatabase($database) {
        $this->database = $database;
    }

    /**
     * Export by DBRef
     * mongoexport --db <database> --collection <collection> --query '{"owner": DBRef("<name>", ObjectId("<id>"))}"' >> <path><collection>.json
     *
     * @param $collection
     * @param $ref
     * @param $name
     * @param $id
     * @author Israel Sotomayor
     */
    public function exportDBRef($collection, $ref, $name, $id) {
        $query = ' --query \'{"' . $ref . '": DBRef("' . $name . '", ObjectId("' . (string) $id . '"))}"\'';
        $this->run($collection, $query);
    }

    /**
     * Export by referenced code
     * mongoexport --db <database> --collection <collection> --query '{"<ref>": ObjectId("<id>")}"' >> <path><collection>.json
     *
     * @param $collection
     * @param $ref
     * @param $id
     * @author Israel Sootmayor
     */
    public function exportObjectId($collection, $ref, $id) {
        $query = ' --query \'{"' . $ref . '": ObjectId("' . (string) $id . '")}"\'';
        $this->run($collection, $query);
    }

    /**
     * Export by _id
     * mongoexport --db <database> --collection <collection> --query '{"_id": ObjectId("<id>")}"' >> <path><collection>.json
     *
     * @param $collection
     * @param $id
     * @author Israel Sotomayor
     */
    public function exportId($collection, $id) {
        $this->exportObjectId($collection, '_id', $id);
    }

    /**
     * Export the whole collection
     * mongoexport --db <database> --collection <collection> >> <path><collection>.json
     *
     * @param $collection
     * @author Israel Sotomayor
     */
    public function export($collection) {
        $this->run($collection);
    }

    /**
     * Delete all json files on the default (the script location) or specified path
     *
     * @author Israel Sotomayor
     */
    public function deleteExportFiles() {
        $command = 'rm ' . $this->path . '*.json';
        exec($command);
    }

    /**
     * Run the mongoexport command and show what is running on the command line
     *
     * @param $collection
     * @param null $query
     * @author Israel Sotomayor
     */
    private function run($collection, $query = null) {
        $mongoExport = 'mongoexport --db ' . $this->database . ' --collection ';
        $out = ' >> ' . $this->path . $collection . '.json';

        $command = isset($query) ? $mongoExport . $collection . $query . $out : $mongoExport . $collection . $out;

        echo $command . "\r\n";
        exec($command);
    }
}