2016-08-19 85 views
2

我创造了一个集“的帖子”有标题,描述,通过评论MongoDB中的各个用户在MongoDB中创造的职位数目:写MapReduce的函数来计算

db.posts.insert({ 
        title:'MongoDB', 
        description:'MongoDB is a NoSQL DB', 
        by:'Tom', 
        comments:[ 
          {user:'ram', 
           message:'We use MongoDB' 
          } 
          ] 
       } 
       ) 

同样,我添加了另外两个条目。 现在,我想写MapReduce函数来统计MongoDB中各种用户创建的帖子数。我用:

db.posts.mapReduce( 
    function() { emit(this.user_id,1); }, 
    function(key, values) {return Array.sum(values)}, {  
     out:"post_total" 
    } 

).find() 

输出:

{"id": null , "value": 3} 

但是,我想显示是这样的:

{ "_id" : "tom_id", "value" : 2 } 
{ "_id" : "mark_id", "value" : 1 } 

{ "by" : "tom", "value" : 2 } 
{ "by" : "mark", "value" : 1 } 

回答

1

最后,我解决了它。我有一些想法来自MapReduce function in MongoDB - Grouping document by ID

db.posts.mapReduce( 
    function() { emit(this.by,1); }, 
    function(key, values) {return Array.sum(values)}, {  
     out:"post_total" 
    } 

).find() 

我做错了什么是放出(这一点。user_id说明,1)。我传错了钥匙。

0

重新写你的mapReduce方法为:

db.posts.mapReduce(
    function() { 
     emit(this.user_id, 1); 
    }, 
    function(key, values) { 
     return Array.sum(values); 
    }, 
    { "out": { "inline": 1 } } 
) 

或使用RunCommand命令与输出收集选项运行一个精简操作:

mr = db.runCommand({ 
    "mapreduce": "posts", 
    "map" : function() { 
     for (var key in this) { emit(this.user_id, 1); } 
    }, 
    "reduce" : function(key, values) { return Array.sum(values); }, 
    "out": "post_total" 
}) 

要得到的结果,对结果集合运行find()

db[mr.result].find() 

使用聚合框架的等效结果仍然更有效率操作:

db.posts.aggregate([ 
    { 
     "$group": { 
      "_id": "$user_id", 
      "count": { "$sum": 1 } 
     } 
    } 
]) 
+0

db.posts.mapReduce( 函数(){ EMIT(this.user_id,1);} , 功能(键,值){ 返回Array.sum(值); },{ “出 “:{ ”内联“:1}} ).find() 输出: [{” ID“:NULL, ”值“:3}] 不工作。 –

+0

@SarojShrestha为什么要将find()添加到内联输出中? – chridam

+0

没有查找()输出 “结果”:[ { “ID”:空, “值”:3 } ] “timeMillis”:15, “计数”:{ “输入”:3, “EMIT”:3, “减少”:3, “输出”:1 }, “OK”:1 } –