【问题标题】:Aggregation Conditional Count on Present Fields当前字段的聚合条件计数
【发布时间】:2015-10-15 08:07:30
【问题描述】:

我正在尝试编写一个聚合来计算有多少文档具有某些字段(即仅在它们存在时才计算它们)。这些对象看起来像这样:

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

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    $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 where true0 where false 以提供条件计数。

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 2022-12-02
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      相关资源
      最近更新 更多