我有一个相当大的MongoDB,我需要从中提取统计数据,我这样做是为了运行Map Reduce查询。
现在的问题是我需要缩小查询范围以使用例如状态:"已起草"而不是使用整个集合。
这是我的映射/减少代码(我正在使用代码点火器):我尝试遵循此查询的最后一步,但无法获得结果,因此我认为我添加了错误的语法:http://cookbook.mongodb.org/patterns/unique_items_map_reduce/。
$map = new MongoCode ("function() {
day = Date.UTC(this.created_at.getFullYear(), this.created_at.getMonth(), this.created_at.getDate());
emit ({day: day, _id: this._id}, {created_at: this.created_at, count: 1});
}");
$reduce = new MongoCode ("function( key , values ) {
var count = 0;
values.forEach (function(v) {
count += v['count'];
});
return {count: count};
}");
$outer = $this->cimongo->command (array (
"mapreduce" => "documents",
"map" => $map,
"reduce" => $reduce,
"out" => "stats_results"
));
$map = new MongoCode ("function() {
emit(this['_id']['day'], {count: 1});
}");
$reduce = new MongoCode ("function( key , values ) {
var count = 0;
values.forEach (function(v) {
count += v['count'];
});
return {count: count};
}");
$outer = $this->cimongo->command (array (
"mapreduce" => "stats_results",
"map" => $map,
"reduce" => $reduce,
"out" => "stats_results_unique"
));
关于你的问题的两件事:
1)食谱中的示例对于您要做的事情来说可能有点太复杂了。 这是一个更简单的:
给定一个如下所示的文档结构:
{
"url" : "http://example.com/page8580.html",
"user_id" : "Jonathan.Clark",
"date" : ISODate("2012-06-11T10:59:36.271Z")
}
下面是一些示例 JavaScript 代码,用于运行 map/reduce 作业,该作业将计算每个不同 URL 的访问次数。
// Map function:
map = function() {
emit({ url: this.url }, {count: 1});
}
// Reduce function:
reduce = function(key, values) {
var count = 0;
values.forEach(
function(val) { count += val['count']; }
);
return {count: count};
};
// Run the Map/Reduce function across the 'pageviews' collection:
// Note that MongoDB will store the results in the 'pages_per_day'
// collection because the 'out' parameter is present
db.pageviews.mapReduce(
map, // pass in the 'map' function as an argument
reduce, // pass in the 'reduce' function as an argument
// options
{ out: 'pages_per_day', // output collection
verbose: true } // report extra statistics
);
2) 如果你只想在"pageviews"集合的一个子集上运行 Map/Reduce 函数,你可以指定一个查询来调用 'mapReduce()' 以限制 'map()' 函数将操作的文档数量:
// Run the Map/Reduce function across the 'pageviews' collection, but
// only report on the pages seen by "Jonathan.Clark"
db.pageviews.mapReduce(
map, // Use the same map & reduce functions as before
reduce,
{ out: 'pages_per_day_1user', // output to different collection
query:{ 'user_id': "Jonathan.Clark" } // query descriptor
verbose: true }
);
请注意,如果您不使用 JavaScript,则必须将这些调用转换为您使用的任何编程语言。
3)下面是一个使用PHP调用具有查询条件的Map/Reduce函数的示例:
$outer = $this->cimongo->command (array (
"mapreduce" => "pageviews",
"map" => $map,
"reduce" => $reduce,
"out" => "pages_per_day_1user",
"query" => array( "user_id" => "Jonathan.Clark" )
));
4) 有关映射/减少的详细信息,请参阅以下参考:
- 地图/化简手册页:http://www.mongodb.org/display/DOCS/MapReduce
- 调试映射/缩减:http://www.mongodb.org/display/DOCS/Troubleshooting+MapReduce
在 PHP 中使用 map/reduce:http://us.php.net/manual/en/mongodb.command.php
--威廉