use*_*127 4 mongodb mongodb-query aggregation-framework
我正在尝试编写一个聚合来计算有多少文档具有某些字段(即只有它们存在时才计算它们).对象看起来像这样:
{
"_id" : ObjectId("5617731fe65e0b19101c7039"),
"dateCreated" : ISODate("2015-10-09T07:56:15.068Z"),
"dateSent" : ISODate("2015-10-09T07:56:16.682Z"),
"dateAttempted" : ISODate("2015-10-09T07:56:16.682Z")
},
{
"_id" : ObjectId("561e37bb537d381bb0ef0ae2"),
"dateCreated" : ISODate("2015-10-14T11:08:43.306Z"),
"dateSent" : ISODate("2015-10-14T11:09:51.618Z"),
"dateAttempted" : ISODate("2015-10-14T11:09:51.618Z"),
"dateViewed" : ISODate("2015-10-15T10:09:50.618Z"),
"dateOpened" : ISODate("2015-10-15T10:10:01.618Z")
}
Run Code Online (Sandbox Code Playgroud)
我想迭代所有文档,计算字段存在的位置.期望的输出:
{
"total" : 1000,
"created" : 1000,
"sent" : 990,
"attempted" : 995
"viewed" : 800,
"opened" : 750
}
Run Code Online (Sandbox Code Playgroud)
如果此输出可以每天分组,则可获得奖励积分!我不希望为范围中的每个日期执行新的聚合.
这是我到目前为止所做的,但是没有用; 它为每个字段返回零
[
{
"$group": {
"_id": {
"$dayOfMonth": "$dateCreated"
},
"total": {
"$sum": 1
},
"sent": {
"$sum": "$dateSent"
},
"attempted": {
"$sum": "$dateAttempted"
},
"viewed": {
"$sum": "$dateViewed"
},
"clicked": {
"$sum": "$dateClicked"
}
}
}
]
Run Code Online (Sandbox Code Playgroud)
[
{
"$group": {
"_id": {
"$dayOfMonth": "$dateCreated"
},
"total": {
"$sum": 1
},
"sent": {
"$sum": { "$cond": [ { "$ifNull": [ "$dateSent", false ] }, 1, 0 ] }
},
"attempted": {
"$sum": { "$cond": [ { "$ifNull": [ "$dateAttempted", false ] }, 1, 0 ] }
},
"viewed": {
"$sum": { "$cond": [ { "$ifNull": [ "$dateViewed", false ] }, 1, 0 ] }
},
"clicked": {
"$sum": { "$cond": [ { "$ifNull": [ "$dateClicked", false ] }, 1, 0 ] }
}
}
}
]
Run Code Online (Sandbox Code Playgroud)
$ifNull将返回存在的字段(逻辑true)或备用值false.而且$cond看起来在此条件下,再返回1这里true或0那里虚假提供条件计数.
| 归档时间: |
|
| 查看次数: |
1436 次 |
| 最近记录: |