node.js - 使用 Mongoose 的多个组

标签 node.js mongodb mongoose

我想要获得每家公司所有事件的总和。这是我的数据:

{company: "1" event:"a"}
{company: "1" event:"b"}
{company: "1" event:"c"}
{company: "2" event:"b"}
{company: "2" event:"b"}
{company: "3" event:"c"}
{company: "3" event:"c"}

我目前有这个来汇总事件日期,但我正在努力按公司进一步对它们进行分组:

{
  "aggregate": [

    {
      "$group": {
        "_id": "$event",
        "count": {"$sum": 1}
      }
    },
    {"$sort": {"_id": 1}}
  ]
}

呈现这些结果:

[ { “_id”:“一个”, “计数”:1 }, { “_id”:“b”, “计数”:3 }, { “_id”:“c”, “计数”:2 }]

我如何进一步按公司对事件计数进行分组,以生成以下内容:

 [{
        "_id": {
            "company" :"1",
            "events": [
                {
                    "event": "a",
                    "count": 1
                },
                {
                    "event": "b",
                    "count": 1
                },
                {
                    "event": "c",
                    "count": 1
                },
            ]
        }
    },
    {
        "_id": {
            "company" :"2",
            "events": [
                {
                    "event": "b",
                    "count": 2
                }
            ]
        }
    },
    {
        "_id": {
            "company" :"3",
            "events": [
                {
                    "event": "c",
                    "count": 2
                }
            ]
        }
    }
    ]

我已经在查询中尝试了各种其他组,但无法生成我想要的数据。还有一个警告:我无法处理服务器端的任何内容或更改架构,因此我只能传递我希望能够完成的查询。

最佳答案

db.collection.aggregate([
{
  $group:{
     _id:{company:"$company",event:"$event"},
     count:{$sum:1}
  }
},
{
  $group:{
     _id:"$_id.company",
     events:{$push:{event:"$_id.event",count:"$count"}}
  }
}
])

如果您需要与您提到的完全相同的输出,则添加 $project stage

$project:{_id:{公司:"$_id",事件:"$events"}}

关于node.js - 使用 Mongoose 的多个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47785315/

相关文章:

javascript - 来自默认浏览器的 Electron "grab"localStorage

javascript - 是否有 mongo 替换方法/运算符?

MongoDB 基于间隔分组

node.js - 匹配 Mongoose 中的两个不同字段,聚合?

node.js - Mongoose 对象 id 约束

node.js - 弃用警告 : Listening to events on the Db class has been deprecated and will be removed in the next major version

javascript - sh : 1: concurrent: not found while npm start

node.js - 使用 sequelize 进行子查询以使用日期和时间过滤即将发生的事件

node.js - 生产环境中的 NodeJS 和 Socket.io : Dealing with state

mongodb - mongodb中索引和搜索数字字段