mysql - 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))
,请帮助。
解决方案
尝试以下聚合查询:
脚步 :
- 您将分组
account_id
并转换并有条件地date_posted
检查message_format
字段并传递1
或基于字段值,如果字段是则将被传递,因此在对文档进行分组时,如果有 10 个文档则将 是&其余的将是。0
$sum
null
0
message_format == e
email_count
10
0
- 然后您可以添加从
account_id
.date_posted
$_id
- 使用项目删除不必要
_id
的字段。 - 排序
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-游乐场
参考: 聚合管道运营商
推荐阅读
- kubernetes - 无法使用操作员通过部署在 OpenShift 上的 Couchbase 控制台添加新存储桶
- python - 如何将 NavigationToolbar 所做的更改保留在定期更新的图表上
- scala - Scala:重载方法值与替代方案融合:
- types - 如何在枚举变体上创建一个包含枚举泛型的结构?
- swift - SwiftUI:是否存在修饰符来突出显示 Text() 视图的子字符串?
- bison - 可重入 Bison 解析器的参数未正确反映为 yyerror 的参数
- c# - 获得在 .Net Framework Console 应用程序中工作的安全 .Net Core 代码
- ios - Swift 在递归函数中没有返回正确的值
- c# - ASP.NET 播放视频,开头没有整个字节 []
- c++ - 使用完美转发的衰减