首页 > 解决方案 > MongoDB - 根据字段在小组阶段是否具有特定值来计数文档

问题描述

我写了一个这样的 Mysql 查询:

SELECT account_id,date(date_posted) as date_posted,sum(if(message_format = 'e',1,0)) as email_count,sum(if(message_format = 't',1,0)) as 
sms_count,sum(if(message_format = 'p',1,0)) as push_count,sum(if(message_format = 's',1,0)) as slack_count
FROM `track_notifications` GROUP BY date(date_posted), account_id ORDER BY account_id

MySQL 结果如下图所示:

在此处输入图像描述

我想在MongoDB中获得与 MySQL 结果相同的结果,我是MongoDB的新手。如何在 MongoDB 中编写此查询

我试过这样:

db.Datasets.aggregate([{$project:{_id:0,account_id:1,date_posted:1,message_format:{$ifNull:["$message_format",0]}}},{$sort:{"account_id":1}}])

示例文档:

_id:ObjectId(“5e8851dc53a883900d9b8e4b”)
account_id:52519
date_posted:”2018-11-19T15:38:52.000Z”
message_format:”t”

_id:ObjectId(“5e8851dc53a883900d9b8e4c”)
account_id:52519
date_posted:”2018-11-19T15:43:01.000Z”
message_format:”e”

_id:ObjectId(“5e8851dc53a883900d9b8e4d”)
account_id:52519
date_posted:”2018-11-19T15:38:51.000Z”
message_format:”e”

_id:ObjectId(“5e8851dc53a883900d9b8e4d”)
account_id:52519
date_posted:”2018-11-19T15:56:22.000Z”
message_format:”s”

_id:ObjectId(“5e8851dc53a883900d9b8e4e”)
account_id:52519
date_posted:”2018-11-19T15:56:22.000Z”
message_format:”p”

经过长时间的研究和尝试,我被困在这里sum(if(message_format = 't',1,0)),请帮助。

标签: mysqlmongodbmongodb-queryaggregation-framework

解决方案


尝试以下聚合查询:

脚步 :

  1. 您将分组account_id并转换并有条件地date_posted检查message_format字段并传递1或基于字段值,如果字段是则将被传递,因此在对文档进行分组时,如果有 10 个文档则将 是&其余的将是。0$sumnull0message_format == eemail_count100
  2. 然后您可以添加从account_id.date_posted$_id
  3. 使用项目删除不必要_id的字段。
  4. 排序account_id以按升序排列结果文档。

询问 :

db.track_notifications.aggregate([
      {
        $group: {
          _id: {
            account_id: "$account_id",
            date_posted: {
              $dateToString: { format: "%Y-%m-%d", date: "$date_posted" },
            },
          },
          email_count: {
            $sum: { $cond: [{ $eq: ["$message_format", "e"] }, 1, 0] },
          },
          sms_count: { $sum: { $cond: [{ $eq: ["$message_format", "t"] }, 1, 0] } },
          push_count: {
            $sum: { $cond: [{ $eq: ["$message_format", "p"] }, 1, 0] },
          },
          slack_count: {
            $sum: { $cond: [{ $eq: ["$message_format", "s"] }, 1, 0] },
          },
        },
      },
      {
        $addFields: {
          account_id: "$_id.account_id",
          date_posted: "$_id.date_posted",
        },
      },
      { $project: { _id: 0 } },
      { $sort: { account_id: 1 } },
    ]);  

测试: MongoDB-游乐场

参考: 聚合管道运营商


推荐阅读