mongodb解散数组嵌套在文档数组中 [英] mongodb unwind array nested inside an array of documents
问题描述
在MongoDB中,我需要能够展开嵌套在主文档内部数组中的文档中的数组.
In MongoDB, I need to be able to unwind nested an array in a document inside an array inside the main document.
{
"_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).
Based on the record above I need to count the job labels (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"
}
]
如何获得此输出?
推荐答案
In unwind stage, field should be an array field. If not array field, it treats it as array of 1 element.
在3.2版中进行了更改:$ unwind stage不再在非数组操作数上出错.如果操作数不能解析为数组,但不丢失,为null或为空数组,则$ unwind会将操作数视为单个元素数组.
Changed in version 3.2: $unwind stage no longer errors on non-array operands. If the operand does not resolve to an array but is not missing, null, or an empty array, $unwind treats the operand as a single element array.
回答您的查询:
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 输出
这篇关于mongodb解散数组嵌套在文档数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!