【问题标题】:Multiples group aggregate in mongodbMongoDB中的倍数组聚合
【发布时间】:2015-04-01 13:55:08
【问题描述】:

假设我收藏了这样的书籍:

{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 }

但我不明白如何使用类别执行第二个“分组依据”。
最好的方法是什么?

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 您可以使用 $project 来进一步塑造 OP 想要的结果:> db.books.aggregate([ {$group: { _id: {category: '$category', author: '$author'}, result: {$sum: 1} }}, {$project: {_id: "$_id.author", result : "$result" }} ])
    • 你知道我怎么能像这样的项目:{ autor : 'john', list: {action:2, scifi:3, novel:0 }} 吗?
    • @AbelChalier 最好将其作为一个新问题发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2021-04-28
    • 2014-12-01
    • 2021-11-20
    • 2015-12-06
    相关资源
    最近更新 更多