mongo如何按组字段对文档进行分组

时间:2019-04-02 15:00:36

标签: mongodb mongodb-query aggregation-framework

我无法对文档进行分组。首先,我想按“ field1”分组,之后我要与“ field2”进行新分组。怎么可能呢?看这个例子,谢谢你们。

我正在使用汇总

我的文档示例:

{
    field1: 1,
    field2: 2,
    name: 'ABC'
},
{
    field1: 1,
    field2: 2,
    name: 'ABC'
},
{
    field1: 2,
    field2: 3,
    name: 'ABC'
}

预期结果:

[
   {
      "field1":1,
      "data":[
         {
            "field2":2,
            "data":[
               {
                  "name":"ABC"
               },
               {
                  "name":"ABC"
               }
            ]
         }
      ]
   },
   {
      "field1":2,
      "data":[
         {
            "field2":3,
            "data":{
               "name":"ABC"
            }
         }
      ]
   }
]

1 个答案:

答案 0 :(得分:1)

您可以在aggregation下使用

db.collection.aggregate([
  { "$group": {
    "_id": { "field1": "$field1", "field2": "$field2" },
    "data": { "$push": { "name": "$name" }}
  }},
  { "$group": {
    "_id": "$_id.field1",
    "data": {
      "$push": {
        "field2": "$_id.field2",
        "data": "$data"
      }
    }
  }},
  { "$project": { "_id": 0, "data": 1, "field1": "$_id" }}
])