我正在使用mongo版本3.4.3,我将我的文档存储在mongo中,就像这样 -
{
"_id" : ObjectId("5ad5ab8aaf2808b739ba6ab2"),
"ResumeId" : "105839064",
"ResumeDetails" : {
"WorkProfile" : [
{
"Company" : "XXXXXXXXX",
"JobTitle" : "YYYYY",
"JobSkills" : {
"CommonSkills": [],
"OtherSkills": []
}
},
{
"Company" : "XXXXXXXX",
"JobTitle" : "YYYYYY",
"JobSkills" : {
"CommonSkills" : [
ObjectId("5ad5ab860b94c96c738e914a")
],
"OtherSkills" : [
ObjectId("5ad5ab860b94c96c738e9146")
]
}
},
{
"Company" : "XXXXXXX",
"JobTitle" : "YYYY"
}
],
"AdditionalSkills" : {
"CommonSkills" : [
ObjectId("5ad5ab860b94c96c738e9175"),
ObjectId("5ad5ab860b94c96c738e91f0"),
ObjectId("5ad5ab860b94c96c738e9241"),
ObjectId("5ad5ab860b94c96c738e919b")
],
"OtherSkills" : [
ObjectId("5ad5ab860b94c96c738e90e6"),
ObjectId("5ad5ab860b94c96c738e9142"),
ObjectId("5ad5ab860b94c96c738e9211"),
ObjectId("5ad5ab860b94c96c738e9293"),
ObjectId("5ad5ab860b94c96c738e92c8")
]
}
},
"DocId" : "51cb2f49-fcb9-46a0-9040-67e0f986be11"
}
我希望将WorkProfile和AdditionalSkills下的所有技能结合在2个独立的数组下。我尝试了以下查询
db.ResumeParsedData.aggregate([
{$match: {'DocId': '51cb2f49-fcb9-46a0-9040-67e0f986be11'}},
{$project: {
'JobSkills': {'$concatArrays': [
'$ResumeDetails.WorkProfile.JobSkills.CommonSkills', '$ResumeDetails.WorkProfile.JobSkills.OtherSkills']
},
'AdditionalSkills': {'$setUnion': [
'$ResumeDetails.AdditionalSkills.CommonSkills', '$ResumeDetails.AdditionalSkills.OtherSkills']},
}
}]).pretty()
但我得到以下输出 -
{
"_id" : ObjectId("5ad5ab8aaf2808b739ba6ab2"),
"JobSkills" : [
[
ObjectId("5ad5ab860b94c96c738e914a")
],
[
ObjectId("5ad5ab860b94c96c738e9146")
]
],
"AdditionalSkills" : [
ObjectId("5ad5ab860b94c96c738e90e6"),
ObjectId("5ad5ab860b94c96c738e9142"),
ObjectId("5ad5ab860b94c96c738e9175"),
ObjectId("5ad5ab860b94c96c738e919b"),
ObjectId("5ad5ab860b94c96c738e91f0"),
ObjectId("5ad5ab860b94c96c738e9211"),
ObjectId("5ad5ab860b94c96c738e9241"),
ObjectId("5ad5ab860b94c96c738e9293"),
ObjectId("5ad5ab860b94c96c738e92c8")
]
}
如何修复JobSkills数组字段。它目前是作为数组字段的数组。
我还尝试了concatArrays
两次:
db.ResumeParsedData.aggregate([
{$match: {'DocId': '51cb2f49-fcb9-46a0-9040-67e0f986be11'}},
{$project: {
'JobSkills': {'$concatArrays': { '$concatArrays': [
'$ResumeDetails.WorkProfile.JobSkills.CommonSkills',
'$ResumeDetails.WorkProfile.JobSkills.OtherSkills'
]}},
'AdditionalSkills': {'$setUnion': [
'$ResumeDetails.AdditionalSkills.CommonSkills',
'$ResumeDetails.AdditionalSkills.OtherSkills'
]},
} }
]).pretty()
答案 0 :(得分:2)
您可以使用$reduce(3.4中提供)来展平您的数组阵列:
db.ResumeParsedData.aggregate([
{ $match: {"DocId": "51cb2f49-fcb9-46a0-9040-67e0f986be11"} },
{
$project: {
"JobSkills": {
$reduce: {
input: {
$concatArrays: ["$ResumeDetails.WorkProfile.JobSkills.CommonSkills", "$ResumeDetails.WorkProfile.JobSkills.OtherSkills"]
},
initialValue: [],
in: { $setUnion: [ "$$this", "$$value" ] }
}
},
"AdditionalSkills": {"$setUnion": [
"$ResumeDetails.AdditionalSkills.CommonSkills", "$ResumeDetails.AdditionalSkills.OtherSkills"]}
}
}
])
$setUnion保证最终数组
中没有重复项