mongodb unwind数组嵌套在一个文档数组中

时间:2016-10-21 04:55:42

标签: mongodb aggregation-framework

在MongoDB中,我需要能够在主文档内的数组内的文档中展开嵌套数组。

{
    "_id" : ObjectId("5808d700536d1a3d69f4cf51"),
    "last_name" : "Maity",
    "xiith_mark" : 58,
    "id" : "3539488",
    "first_name" : "Harshavardhan",
    "course_name" : "BE/B.Tech",
    "institute_name_string" : "Abhayapuri College, P.O. Abhayapuri",
    "profile_percentage" : 45,
    "xiith_mark_type" : "Percentage",
    "xth_mark_type" : "Percentage",
    "date_of_birth" : "14-April-1993",
    "xth_mark" : 30,
    "last_login" : 1470827224,
    "percentage" : 55,
    "job_details" : [
        {
            "status" : NumberLong(6),
            "applied_date" : NumberLong(1470831441),
            "job_id" : NumberLong(92928),
            "contact_viwed_status" : 0,
            "label_name" : [
                "shortlisted",
                "rejected"
            ],
            "questionnaire_status" : 0,
            "batch_id" : NumberLong(6),
            "call_letter" : NumberLong(812)
        }, 
        {
            "status" : NumberLong(6),
            "applied_date" : NumberLong(1470831441),
            "job_id" : NumberLong(92928),
            "contact_viwed_status" : 0,
            "label_name" : [
                "shortlisted",
                "rejected"
            ],
            "questionnaire_status" : 0,
            "batch_id" : NumberLong(6),
            "call_letter" : NumberLong(812)
        }
    ],
    "branch_name" : "Applied Electronics",
    "candidate_state_name" : "West Bengal",
    "candidate_city_name_string" : "Kolkata",
    "10" : 10,
    "12" : 12,
    "skills" : "",
    "gender" : "Male",
    "fw_id" : "FW15884830",
    "cgpa" : 0,
    "picture_path" : "",
    "hq_passout_year" : 2019
}

根据上面的记录,我需要计算作业标签(job_details.label_name)。

我尝试了以下查询:

db.response.aggregate(
    {"$match":type_match},
    {"$unwind": "$job_details" }, 
    {"$group": 
      {
        "_id":"$job_details.label_name",
        "count": {"$sum": 1 }
      }
    }
])

输出结果为:

{
   "count": 2,
   "_id": [
   "shortlisted",
   "rejected"
    ]
}

但我希望输出为:

[
  { 
      "count": 1,  
      "_id": "shortlisted"  
  },  
  {  
      "count": 1,  
      "_id": "rejected"  
  }
]

如何获得此输出?

1 个答案:

答案 0 :(得分:7)

unwind阶段,字段应为数组字段。如果不是数组字段,则将其视为1个元素的数组。

来自文档:

在版本3.2中更改:$ unwind阶段不再是非数组操作数上的错误。如果操作数没有解析为数组但没有丢失,null或空数组,则$ unwind将操作数视为单个元素数组。

回答您的疑问:

db.response.aggregate([
    {
        $project:
        {
            "job_details.label_name":1,
            _id:0
        }
    },
    {
        $unwind:"$job_details.label_name"
    },
    {
        $group:
        {
            _id:"$job_details.label_name",
            count:{$sum:1}
        }
    }
])

参考Shell Output