当前字段的聚合条件计数

时间:2015-10-15 08:07:30

标签: 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")
}

我想迭代所有文档,计算字段存在的位置。期望的输出:

{
        "total" : 1000,
        "created" : 1000,
        "sent" : 990,
        "attempted" : 995
        "viewed" : 800,
        "opened" : 750
}

如果此输出可以每天分组,则可获得奖励积分!我不想为范围内的每个日期执行新的聚合。

这是我到目前为止所做的,但是没有用;它为每个字段返回零

[
  {
    "$group": {
      "_id": {
        "$dayOfMonth": "$dateCreated"
      },
      "total": {
        "$sum": 1
      },
      "sent": {
        "$sum": "$dateSent"
      },
      "attempted": {
        "$sum": "$dateAttempted"
      },
      "viewed": {
        "$sum": "$dateViewed"
      },
      "clicked": {
        "$sum": "$dateClicked"
      }
    }
  }
]

1 个答案:

答案 0 :(得分:7)

$cond$ifNull运营商是这里的帮手:

[
  {
    "$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 ] }
      }
    }
  }
]

$ifNull将返回存在的字段(逻辑true)或备用值false$cond查看此条件并返回1其中true0其中为false以提供条件计数。