Created
November 4, 2011 15:59
-
-
Save mehlah/1339693 to your computer and use it in GitHub Desktop.
Li3 mapReduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Execute a Map/Reduce query against a MongoDb connection | |
* | |
* @param string $map The Javascript Map function code, or if $systemJs=true the stored map procedure | |
* @param string $reduce The optional reduce function code, or if $systemJs=true the stored reduce procedure | |
* @param boolean $systemJs If true, $map/$reduce will be considered stored procs in system.js | |
* | |
* @return object A result of the map/reduce query | |
*/ | |
public static function mapReduce($map, $reduce = null, $systemJs = false, $options = array()) { | |
$source = static::meta('source'); | |
if(isset($options['source'])) { | |
$source = $options['source']; | |
unset($options['source']); | |
} | |
if($systemJs) { | |
$map = "function() { return $map(this); }"; | |
if(is_null($reduce)) { | |
$reduce = "function() {}"; | |
} else { | |
$reduce = "function(k,v) { return $reduce(k,v); }"; | |
} | |
} else { | |
if(is_null($reduce)) { | |
$reduce = "function() {}"; | |
} | |
} | |
$cmdOptions = array( | |
'mapreduce' => $source, | |
'map' => new \MongoCode($map), | |
'reduce' => new \MongoCode($reduce) | |
); | |
$cmdOptions = $cmdOptions + $options; | |
$query = static::connection()->connection->command($cmdOptions); | |
if (!(bool) $query['ok']) { | |
return null; | |
} | |
$result = new Result(array( | |
'resource' => static::connection()->connection->{$query['result']}->find() | |
)); | |
return static::connection()->item(get_called_class(), array(), compact('result') + array( | |
'class' => 'set' | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment