【问题标题】:Use Aggregate with $group in mongodb在 mongodb 中使用 Aggregate 和 $group
【发布时间】:2019-05-24 03:28:35
【问题描述】:

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

/* 1 */
{
    "_id" : ObjectId("5c21d780f82aa31334ab6506"),
    "isBilling" : true,
    "hours" : 6,
    "userId" : ObjectId("5c1f38a1d7537d1444738493"),
}

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

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

我必须创建一个聚合查询来汇总小时数,其中 isBilling 等于 true,并且 isBilling 等于 false。我想要以下输出:

{
 "billingHours":10,
 "fixContract":8
}

我必须使用特定的 userId 获取数据。我尝试了以下方法:

Worksheet.aggregate([
  {
        $match: conditions
  },
  {
      $lookup:{
          "from": "worksheets",
          "let": {},
          "pipeline": [
            { "$match": { "$expr": { "$eq": [ "$isBilling",false] } } },
            { 
              "$group": { "_id": null, "totalHours": { "$sum": "$hours" } }
            },
          ],
          "as": "billingHours"
      }
  },
  {
        "$project":{"billingHours":1}
  }
])

我得到以下结果:

[
    {
        "_id": "5c21d780f82aa31334ab6506",
        "billingHours": [
            {
                "_id": null,
                "totalHours": 16
            }
        ]
    },
    {
        "_id": "5c21d780f82aa31334ab6507",
        "billingHours": [
            {
                "_id": null,
                "totalHours": 16
            }
        ]
    }
]

我不知道为什么它给了我 16 个小时而不是 10 个小时,给了我两个对象而不是 1 个。

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您无需在此处使用$lookup。简单的$group$cond 就可以完成这项工作。

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

    【讨论】:

    • 我不能在同一个集合上使用 $lookup 吗?
    • 不知道你在这里问什么。
    • 我不能使用上面我写的查询吗?
    • 你写的查询没有意义。你为什么用同一个集合做一个$lookup
    • 是的,我也想过。但我没有其他选择。但是你解决了我的问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多