我正在努力让mongodb查询正常工作。下面是我的示例集合。如您所见,图片List是一个可选的嵌套数组。
{
"firstName" : "Mark",
"gender" : "M",
"PictureList":[]
},
{
"firstName" : "Jane",
"gender" : "F",
"PictureList":[]
},
{
"firstName" : "Mary",
"gender" : "F",
"PictureList" : [{"name" : "20151128_233939.jpg","dpInd" : "N"},
{"name" : "20150712_231715.jpg","dpInd" : "Y"}
]
}
我的问题是?我需要
在级别2应用另一个过滤器,仅从dpInd =" Y"的嵌套数组中提取记录。如果不满足此条件,则仅针对嵌套数组显示空结果。我的预期结果是
{
"firstName" : "Jane",
"gender" : "F",
"PictureList":[]
}
{
"firstName" : "Mary",
"gender" : "F",
"PictureList" : [{"name" : "20150712_231715.jpg","dpInd" : "Y"}]
}
答案 0 :(得分:0)
您需要$project
您的文档并使用$map
运算符返回一系列与您的critera匹配的子文档,并使用$cond
运算符返回false
。您可以使用$setDifference
运算符从数组中过滤出false
。
db.people.aggregate([
{ "$match": { "gender": "F" } },
{ "$project": {
"firstName": 1,
"gender": 1,
"PictureList": {
"$setDifference": [
{ "$map": {
"input": "$PictureList",
"as": "pl",
"in": {
"$cond": [
{ "$eq": [ "$$pl.dpInd", "Y" ] },
"$$pl",
false
]
}
}},
[false]
]
}
}}
])
哪个收益率:
{
"_id" : ObjectId("566660b147d21084f02042b3"),
"firstName" : "Jane",
"gender" : "F",
"PictureList" : [ ]
}
{
"_id" : ObjectId("566660b147d21084f02042b4"),
"firstName" : "Mary",
"gender" : "F",
"PictureList" : [
{
"name" : "20150712_231715.jpg",
"dpInd" : "Y"
}
]
}