在mongodb中与$ sum聚合

时间:2018-12-27 07:11:33

标签: mongodb mongodb-query aggregation-framework

我在worksheets集合中有数据,如下所示:

/* 1 */
{
    "_id" : ObjectId("5c21d780f82aa31334ab6506"),
    "isBilling" : true,
    "hours" : 6,
    "userId" : ObjectId("5c1f38a1d7537d1444738467"),
    "projectId": ObjectId("5c1f38a1d7537d1444731234");
}

/* 2 */
{
    "_id" : ObjectId("5c21d780f82aa31334ab6507"),
    "isBilling" : true,
    "hours" : 4,
    "userId" : ObjectId("5c1f38a1d7537d1444738493"),
    "projectId": ObjectId("5c1f38a1d7537d1444734567");
}

/* 3 */
{
    "_id" : ObjectId("5c21e10fae07cc1204a5b647"),
    "isBilling" : false,
    "hours" : 8,
    "userId" : ObjectId("5c1f388fd7537d1444738492"),
    "projectId": ObjectId("5c1f38a1d7537d1444731234");
}

我正在使用以下汇总查询来获取字段总数:

Worksheet.aggregate([
  {
    $match: conditions
  },
  {
   "$group": {
      "_id": null,
      "billingHours": {
        "$sum": {
          "$cond": [{ "$eq": ["$isBilling", true] }, "$hours", 0]
        }
      },
      "fixContract": {
        "$sum": {
          "$cond": [{ "$eq": ["$isBilling", true] }, 0, "$hours"]
        }
      }
    }
  }
])

现在,我想要唯一的projectId字段的总和。上面是 2 。我通过在上面实现的查询中应用两个$ group来尝试它。但这是行不通的。我想得到如下结果:

[
  {
    "_id": null,
    "billingHours": 0,
    "fixContract": 8,
    "totalProjects": 2
  }
]

1 个答案:

答案 0 :(得分:1)

使用$addToSet累加器,然后使用$size运算符来计算唯一projectId的数量

Worksheet.aggregate([
  { $match: conditions },
  { "$group": {
    "_id": null,
    "billingHours": {
      "$sum": {
        "$cond": [{ "$eq": ["$isBilling", true] }, "$hours", 0]
      }
    },
    "fixContract": {
      "$sum": {
        "$cond": [{ "$eq": ["$isBilling", true] }, 0, "$hours"]
      }
    },
    "projectIds": { "$addToSet": "$projectId" }
  }},
  { "$addFields": { "projectIds": { "$size": "$projectIds" }}}
])