我有这样的文件-
{
"Details": "WorkProfile" : [
{
"Company" : "UPS",
"JobTitle" : "Preload Package Handler",
"JobSkills" : {
"CommonSkills" : [
ObjectId("5ad5ab860b94c96c738e911e")
],
"OtherSkills" : [
ObjectId("5ad5ab860b94c96c738e9208")
]
}
},
{
"Company" : "L&L Tent and Party",
"JobTitle" : "Delivery Driver/ Tent Installation",
"JobSkills" : {
"CommonSkills" : [
ObjectId("5ad5ab860b94c96c738e9227")
],
"OtherSkills" : [ ]
}
},
{
"Company" : "All Pro Movers",
"JobTitle" : "Mover"
},
{
"Company" : "Carolina Farmin",
"JobTitle" : "Head of Cullinary"
}
],
}
我想为OtherSkills
部分中的每个子文档获取WorkProfile
。我尝试了以下
db.Collection.aggregate([{$match: {"DocId": "669f4a8f-13cd-4780-8115-e3f29b0d9b4f"}}, {$project: {"JobSkills": "$Details.WorkProfile.JobSkills.OtherSkills"}}]).pretty()
{
"_id" : ObjectId("5ad5ab89af2808b739ba6aac"),
"JobSkills" : [
[
ObjectId("5ad5ab860b94c96c738e9208")
],
[ ]
]
}
现在,如果该子文档中不存在该字段,那么我想为该字段设置默认值。为此,我尝试使用$ifNull这样的命令
db.ResumeParsedData.aggregate([{$match: {"DocId": "669f4a8f-13cd-4780-8115-e3f29b0d9b4f"}}, {$project: {"JobSkills": {$ifNull: ["$ResumeDetails.WorkProfile.JobSkills.OtherSkills", "null"]}}}]).pretty()
{
"_id" : ObjectId("5ad5ab89af2808b739ba6aac"),
"JobSkills" : [
[
ObjectId("5ad5ab860b94c96c738e9208")
],
[ ]
]
}
但是我得到的结果与我的第一个查询相同。如果子文档中不存在该字段,我应该如何为该字段指定默认值。
我期望上述文档的输出-
{
"_id" : ObjectId("5ad5ab89af2808b739ba6aac"),
"JobSkills" : [
[
ObjectId("5ad5ab860b94c96c738e9208")
],
[ ],
"null",
"null"
]
}
答案 0 :(得分:1)