Multiples组聚合在mongodb中

时间:2015-02-02 15:13:37

标签: node.js mongodb mongoose mongodb-query

假设我有这样的书籍集合:

{author:"john",  category:"action", title:"foobar200"},  
{author:"peter", category:"scifi" , title:"42test"},  
{author:"peter", category:"novel",  title:"whatever_t"},  
{author:"jane",  category:"novel",  title:"the return"},  
{author:"john",  category:"action", title:"extreme test"},  
{author:"peter", category:"scifi",  title:"such title"},  
{author:"jane",  category:"action", title:"super book "}

我想进行类似的查询:
SELECT author,category, count(*) FROM books GROUP BY category, author
==>结果:

john -> action -> 2  
john -> novel  -> 0  
john -> scifi  -> 0  
jane -> action -> 1
etc...

最接近解决方案的是:

 db.books.aggregate(
       { 
         $match: {category:"action"} 
        }, 
       {
         $group: { _id: '$author', result: { $sum: 1 } } 
      }
);

==>结果

{ "_id" : "jane",  "result" : 1 }
{ "_id" : "john",  "result" : 2 }
{ "_id" : "peter", "result" : 0 }

但是我无法理解如何通过"来执行第二组#34;与类别。
 这样做的最佳方式是什么?

由于

1 个答案:

答案 0 :(得分:0)

您可以在_id使用的$group中添加多个字段,以提供多字段分组:

db.books.aggregate([
    {$group: {
        _id: {category: '$category', author: '$author'}, 
        result: {$sum: 1}
    }}
])

结果:

{
    "_id" : {
        "category" : "action",
        "author" : "jane"
    },
    "result" : 1
}, 
{
    "_id" : {
        "category" : "novel",
        "author" : "jane"
    },
    "result" : 1
}, 
{
    "_id" : {
        "category" : "novel",
        "author" : "peter"
    },
    "result" : 1
}, 
{
    "_id" : {
        "category" : "scifi",
        "author" : "peter"
    },
    "result" : 2
}, 
{
    "_id" : {
        "category" : "action",
        "author" : "john"
    },
    "result" : 2
}