mongodb – 如何映射 – 减少组,排序和计算排序值

我有mapreduce的一些问题.

我想对集合中的一些值进行分组,排序和计数.我收藏如下:

----------------------------
| item_id    |    date      |
----------------------------
| 1          | 01/15/2012   | 
----------------------------
| 2          | 01/01/2012   |
---------------------------- 
| 1          | 01/15/2012   |
----------------------------  
| 1          | 01/01/2012   |
----------------------------
| 2          | 01/03/2012   |
----------------------------
| 2          | 01/03/2012   |
----------------------------
| 1          | 01/01/2012   |
----------------------------
| 1          | 01/01/2012   |
----------------------------
| 2          | 01/01/2012   |
----------------------------
| 2          | 01/01/2012   |
----------------------------

我想按item_id进行分组,并按日计算每个项目的日期和每个项目的排序日期,并获得如下结果:

value: {{item_id:1, date:{01/01/2012:3, 01/15/2012:2 }},{item_id:2, date:{01/01/2012:3, 01/03/2012:2 }}}

我用mapReduce:

m=function()
{
   emit(this.item_id, this.date);
}
r=function(key, values)
{
var res={};
values.forEach(function(v)
{
if(typeof res[v]!='undefined') ? res[v]+=1 : res[v]=1;
});
return res;
}

但我没有收到如下结果:

{{item_id:1, date:{01/01/2012:3, 01/15/2012:2 }},{item_id:2, date:{01/01/2012:3, 01/03/2012:2 }}}

有任何想法吗?

最佳答案 给出表格的输入文件:

> db.dates.findOne()
{ "_id" : 1, "item_id" : 1, "date" : "1/15/2012" }
> 

以下map和reduce函数应该生成您要查找的输出:

var map = function(){
    myDate = this.date;
    var value = {"item_id":this.item_id, "date":{}};
    value.date[myDate] = 1;
    emit(this.item_id, value);
}

var reduce = function(key, values){
    output = {"item_id":key, "date":{}};
    for(v in values){
        for(thisDate in values[v].date){
            if(output.date[thisDate] == null){
                output.date[thisDate] = 1;
            }else{
                output.date[thisDate] += values[v].date[thisDate];
            }
        }
    }
    return output;
}

> db.runCommand({"mapReduce":"dates", map:map, reduce:reduce, out:{replace:"dates_output"}})

> db.dates_output.find()
{ "_id" : 1, "value" : { "item_id" : 1, "date" : { "1/15/2012" : 2, "1/01/2012" : 3 } } }
{ "_id" : 2, "value" : { "item_id" : 2, "date" : { "1/01/2012" : 3, "1/03/2012" : 2 } } }

希望上面的内容可以满足您的需求,或者至少让您指向正确的方向.

有关将Map Reduce与MongoDB一起使用的更多信息,请参阅Mongo文档:
http://www.mongodb.org/display/DOCS/MapReduce

MongoDB Cookbook中还有一些额外的Map Reduce示例:
http://cookbook.mongodb.org/

有关如何运行Map Reduce操作的分步演练,请参阅MongoDB Cookbook配方的“Extras”部分“使用版本化文档查找最大值和最小值”http://cookbook.mongodb.org/patterns/finding_max_and_min/

祝好运!

点赞