[英]MongoDB - Count documents based on if a field has a particular value in group stage
我寫了一個 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 結果如下圖所示:
我想得到與 MySQL 結果相同的MongoDB ,我是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
或0
傳遞給$sum
,如果字段是null
則將傳遞0
,因此在對文檔進行分組時,如果 10 個文檔具有message_format == e
然后email_count
將是10
& rest others 將是0
。$_id
中提取的account_id
和date_posted
字段。_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 } },
]);
參考:聚合管道運營商
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.