2016-04-25 62 views
1

示例数据:计数文件由某一特定领域分组

{ "category" : "abc" } 
{ "category" : "abc", "ready": true } 
{ "category" : "xyz" } 
{ "category" : "foo", "ready": true } 
{ "category" : "foo", "ready": true } 
{ "category" : "foo" } 

预期输出:

{ 
    "abc": { 
     "count": 2, 
     "ready": 1 
    }, 
    "xyz": { 
     "count": 1, 
     "ready": 0 
    }, 
    "foo": { 
     "count": 3, 
     "ready": 2 
    } 
} 

而且这将是很好,如果我可以选配,从迄今作出的那种给一个按天或月份统计。

谢谢!

+0

你具体要使用的map-reduce? – BanksySan

+0

nope - 无论什么作品 – Tobias

+0

你确实需要它的格式吗?或者这个工作适合你吗?{“_id”:“foo”,“count”:3,“ready”:2}' – kryshna

回答

1

在这里你去:

db.foo.aggregate([{ 
    $group: { 
     _id: "$category", 
     count: { $sum: 1}, 
     ready: { 
      $sum: { 
       $cond: { 
        if: "$ready", 
        then: 1, 
        else: 0 
       } 
      } 
     } 
    } 
}]) 

返回:

/* 1 */ 
{ 
    "_id" : "foo", 
    "count" : 3, 
    "ready" : 2 
} 

/* 2 */ 
{ 
    "_id" : "xyz", 
    "count" : 1, 
    "ready" : 0 
} 

/* 3 */ 
{ 
    "_id" : "abc", 
    "count" : 2, 
    "ready" : 1 
} 
+0

真棒!任何建议如何在那里得到一个查询? ts> date和ts Tobias

+0

是的,你只需要在组之前添加一个匹配阶段。 – BanksySan

+0

明白了!万分感谢! – Tobias