node.js - mongodb 中的多个组聚合

标签 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 "}

我想做一个类似于以下的查询:
按类别、作者从图书组中选择作者、类别、计数(*)
==> 结果:

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 }

但我无法理解如何使用类别执行第二个“分组依据”。
做到这一点的最佳方法是什么?

谢谢

最佳答案

您可以在 $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
}

关于node.js - mongodb 中的多个组聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28280804/

相关文章:

c# - MongoDB NoRM : query nested objects using Expando

c# - 日期之间的 MongoDB C# 驱动程序聚合返回空字段

javascript - 无法完成 GET 请求

javascript - 从数组内部计算每个键的不同值

node.js - 如何在 Node 调试器中禁用 "break on first line"

node.js - 如何使用 Node JS 或命令行将图像从服务器复制到本地

node.js - gatsby 构建在 netlify 上失败并抛出 new ERR_REQUIRE_ESM(filename, ParentPath, packageJsonPath);

javascript - find 查询查找检索 mongodb 中特定元素的数据

http - HTTP响应 header 中 'Allow'和 'Access-Control-Allow-Methods'之间的区别?

node.js - EJS 在某些情况下只输出第一个找到的用户