【问题标题】:Display mongodb multiple group by query results in a nested format以嵌套格式显示 mongodb 多组查询结果
【发布时间】:2015-06-05 21:18:38
【问题描述】:

给定以下数据集:

[
  {
    "account_id" : "1111"
    "task_id" : "aaaa",
    "workweek" : "20",
    "hours": "18"
  },
  {
    "account_id" : "1111"
    "task_id" : "aaaa",
    "workweek" : "20",
    "hours": "12"
  },
  {
    "account_id" : "1111"
    "task_id" : "aaaa",
    "workweek" : "21",
    "hours": "10"
  },
  {
    "account_id" : "1111"
    "task_id" : "bbbb",
    "workweek" : "21",
    "hours": "5"
  },
  {
    "account_id" : "2222"
    "task_id" : "cccc",
    "workweek" : "21",
    "hours": "15"
  }
]

我想对文档进行分组,并获得以下格式的结果:

[
  {
    "account_id": "1111",
    "tasks": [
      {
        "task_id": "aaaa",
        "workweeks": [
          {
            "workweek": "20",
            "total_hours": "30" 
          },
          {
            "workweek": "21",
            "total_hours": "10" 
          }
        ]
      },
      {
        "task_id": "bbbb",
        "workweeks": [
          {
            "workweek": "21",
            "total_hours": "5" 
          }
        ]
      }
    ]
  },
  {
    "account_id": "2222",
    "tasks": [
      {
        "task_id": "cccc",
        "workweeks": [
          {
            "workweek": "21",
            "total_hours": "15" 
          }
        ]
      },
    ]
  }
]

我损坏的聚合代码如下:

db.tasks.aggregate([
  {"$group": { 
    "_id": {
      "account_id": "$account_id", 
      "task_id": "$task_id",
      "workweek": "$workweek",
    },
    "total_hours": {$sum: "$hours"}
  }},
  {"$group": { 
    "_id": "$_id.account_id",
    "tasks": { 
      "$push": {
        "task_id": "$_id.task_id",
        "workweeks": {
          "$push": {
            "workweek": "$_id.workweek",
            "total_hours": "$total_hours"  
          }
        }
      }
    }
  }}
]);

我收到此错误: "errmsg" : "异常:无效的运算符 '$push'", 我认为这是因为每个 $group 块我只能 $push 一次。

关于如何达到预期结果的任何想法?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    请尝试额外的(中间件)“分组”步骤:

    db.tasks.aggregate([
      {"$group": { 
        "_id": {
          "account_id": "$account_id", 
          "task_id": "$task_id",
          "workweek": "$workweek",
        },
        "total_hours": {$sum: "$hours"}
      }},
      {"$group": { 
        "_id": { 
            "$_id.account_id",
            "$_id.task_id"
        },
        "workweeks": {
          "$push": {
            "workweek": "$_id.workweek",
            "total_hours": "$total_hours"  
          }
        }
      }},
      {"$group": { 
        "_id": "$_id.account_id",
        "tasks": { 
          "$push": {
            "task_id": "$_id.task_id",
            "workweeks": "$workweeks"
          }
        }
      }}
    ]);
    

    【讨论】:

    • 很好 :) 真的很高兴它有帮助。
    猜你喜欢
    • 2021-08-13
    • 2017-01-26
    • 2015-01-19
    • 1970-01-01
    • 2021-06-29
    • 2013-06-22
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多