MongoDB如何按数组内部定义的所有字段进行分组?

时间:2017-11-12 05:17:51

标签: mongodb mongoose aggregation

我的文档结构如下:

{
  "workType": "String",
  "functionalArea": [],
  "gender": Boolean,
  "contractType": String    
}

我有一组字段,我想按这些字段对数据进行分组:

groupByFields = [
  "gender", "workType", "functionalArea"
]; 

我的当前函数使用单个字段而不是字段数组来按数据分组。

queryFilter = {aggregationField: "workType"};
db.getCollection('myCollection').aggregate([
  {
    $match: match
  },
  {
    $group: {
      _id: { $ifNull: ["$" + queryFilter.aggregationField, "Unknown"] },
      total: { $sum: 1 }
    }
  }
])

但是如果我使用数组中的所有字段从数组到组,我怎么能这样做? 我的样本数据:

{
    "_id" : ObjectId("59e4540bf14f1607b90ffb81"),
    "minimumEducation" : "Doctorate",
    "functionalArea" : ["Education", "Management"],
    "locations" : [ 
        "Germany", 
        "Itly", 
        "Iran"
    ],
    "requiredLanguages" : [ 
        "Arabic", 
        "English", 
        "Russian", 
        "Dari", 
        "French"
    ],
    "gender" : "male",
    "nationalities" : [ 
        "Afghan"
    ],
    "workType" : "Part Time",
    "contractType" : "Permanent",
 },
 {
    "_id" : ObjectId("59e4540bf14f1607b90ffb21"),
    "minimumEducation" : "Master",
    "functionalArea" : ["IT", "Management"],
    "locations" : [ 
        "Germany", 
        "Itly", 
        "US"
    ],
    "requiredLanguages" : [ 
        "Arabic", 
        "English", 
        "Russian", 
        "Dari", 
        "French"
    ],
    "gender" : "male",
    "nationalities" : [ 
        "Afghan"
    ],
    "workType" : "Full Time",
    "contractType" : "Short Term",
}

我的当前查询返回一个字段workType的结果:

{
  _id: "Part Time",
  total: 1
},
{
  _id: "Full Time",
  total: 1 
}

但我想要做的是传递一组字段,我希望按这些字段对数据进行分组,例如["workType", "functionalArea", "contractType", "gender"],并且查询应返回每个字段的数据计数。

如果我使用下面的查询,它会将数据与条件分组,但我想要采取的是每个组的单独结果。

db.getCollection('myCollection').aggregate([
  {
     $match: match
  },
  {
     $group: {
       _id: {workType : {$ifNull: ["$workType", "Unknown"]},functionalArea:{$ifNull: ["$functionalArea", "Unknown"]}},
       total: { $sum: 1 }
     }
   }
  ]);

并返回此结果:

{_id: {workType: "Part Time", functionalArea: "IT Software"}, total: 2}

{_id: {workType: "Full Time", functionalArea: "IT Software"}, total: 23}

{_id: {workType: "Part Time", functionalArea: "Education"}, total: 3}

我想要归来的是:

{_id: [{workType: "Part Time", total: 5}, {functionalArea: "IT Software", total: 25}, {functionalArea: "Education", total: 3}}

0 个答案:

没有答案