通过查询结果以嵌套格式

时间:2015-06-05 21:18:38

标签: mongodb aggregation-framework

给出以下数据集:

[
  {
    "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'”, 而且我认为这是因为我只能每$ $ block一次$ push。

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

1 个答案:

答案 0 :(得分:0)

请尝试另外一个(中间件)“分组”步骤:

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"
      }
    }
  }}
]);