聚合组多重结果

时间:2018-07-27 09:20:18

标签: mongodb aggregation-framework aggregate aggregation

我尝试汇总操作'$ group'.. 我想获得多个分组结果。

我的数据是这个。

items: [
  {
   director: "James",
   category: "fruit",
   name: "apple",
   money: 5000
  },
  {
   director: "James",
   category: "toy",
   name: "dragon",
   money: 15000
  },
  {
   director: "Sam",
   category: "fruit",
   name: "orange",
   money: 3500
  }
]

我想得到结果,这!!

directorList:[
  {
   director: "James",
   money: 20000
  },
  {
   director: "Sam",
   money: 3500
  }
],
categoryList: [
  {
   category: "fruit",
   money: 8500
  },
  {
   category: "toy",
   money: 15000
  }
]

请回答。 谢谢.. !!

2 个答案:

答案 0 :(得分:0)

您可以尝试以下汇总

db.collection.aggregate([
  { "$facet": {
    "directorList": [
      { "$group": {
        "_id": "$director",
        "money": { "$sum": "$money" }
      }},
      { "$project": {
        "_id": false,
        "director": "$_id",
        "money": 1
      }}
    ],
    "categoryList": [
      { "$group:" {
        "_id": "$category",
        "money": { "$sum": "$money" }
      }},
      { "$project": {
        "_id": false,
        "category": "$_id",
        "money": 1
      }}
    ]
  }}
])

输出

[
  {
    "categoryList": [
      {
        "category": "toy",
        "money": 15000
      },
      {
        "category": "fruit",
        "money": 8500
      }
    ],
    "directorList": [
      {
        "director": "Sam",
        "money": 3500
      },
      {
        "director": "James",
        "money": 20000
      }
    ]
  }
]

MongoPlayGround

答案 1 :(得分:0)

我阻止了另一个问题..

items: [
  {
   mart_code : 1,
   director: "James",
   category: "fruit",
   name: "apple",
   money: 5000
  },
  {
   mart_code: 1
   director: "James",
   category: "toy",
   name: "dragon",
   money: 15000
  },
  {
   mart_code: 2,
   director: "Sam",
   category: "fruit",
   name: "orange",
   money: 3500
  }
]

我想得到结果。 mart_code已添加..

martList: [ {
  mart_code: 1,
  directorList:[
  {
   director: "James",
   money: 20000
  }
  ],
  categoryList: [
  {
   category: "fruit",
   money: 5000
  },
  {
   category: "toy",
   money: 15000
  }] 
},
{
  mart_code: 2,
  directorList:[
  {
   director: "Sam",
   money: 3500
  }
  ],
  categoryList: [
  {
   category: "fruit",
   money: 3500
  }]
}
]

我尝试$ facet和$ group,$ project ... 有没有有效的方法?