Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert a PHP Mongo query with Mongo* classes to MongoDB js query. Currently supports MongoId => ObjectId, MongoDate => ISODate, and MongoRegex => RegExp. [VERY ROUGH] -- Wrote this because I was tired of getting stuck and having to port the query by hand.
<?php
class MongoQueryStr {
protected static $indent = 0;
public static function convert($query) {
if(!is_array($query)) {
return false;
}
return self::parseRecursive($query);
}
protected static function parseRecursive($j) {
$q = '';
self::$indent++;
$first = true;
foreach($j as $k => $v) {
$array = is_numeric($k);
if($first) {
$first = false;
if($array)
$q .= "[\n";
else
$q .= "{\n";
}
$q .= str_repeat("\t", self::$indent);
if(!$array)
$q .= "\"$k\": ";
if(is_array($v)) {
$q .= self::parseRecursive($v);
}
else if(is_object($v)) {
$q .= self::convertMongoClass($v);
}
else if(is_numeric($v)) {
$q .= (int) $v;
}
else if(is_bool($v)) {
$q .= $v ? "true" : "false";
}
else {
$q .= "\"$v\"";
}
$q .= ",\n";
}
self::$indent--;
return trim($q, ",\n")."\n".str_repeat("\t", self::$indent).($array ? "]" : "}");
}
protected static function convertMongoClass($instance) {
if($instance instanceof \MongoId) {
return 'ObjectId("'.(string)$instance.'")';
}
if($instance instanceof \MongoDate) {
return 'ISODate("'.date('c', $instance->sec).'")';
}
if($instance instanceof \MongoRegex) {
return 'RegExp('.$instance.')';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.