For the below document, I need to output
1. image arrays which are hsl:1
2. dim.hsl embedded document
The main document
{
"_id" : ObjectId("564b17873b91989fcb4e9707"),
"type" : "article",
"image" : [
{
"name" : "i3",
"hsl" : 1
},
{
"name" : "i1",
"hsl" : 1
},
{
"name" : "i2",
"hsl" : 0,
"ai" : 1
}
],
"dim" : {
"hsl" : {
"path" : "blah"
},
"ai" : {
"path" : "blah"
}
}
My expected output is as below which returns 2 documents from image array and the dim.hsl embedded document
{
"result" : [
{
"_id" : ObjectId("564b17873b91989fcb4e9707"),
"type" : "article",
"image" : [
{
"name" : "i3",
"hsl" : 1
},
{
"name" : "i1",
"hsl" : 1
}
],
"dim" : {
"hsl" : {
"path" : "blah"
}
}
}
],
"ok" : 1.0000000000000000
}
The code attempted below is not returning dim.hsl embedded document back. The logic is included in the code as inline. I am not sure on mongodb expressions for checking node presence. So i have used {$not : {$not : '$hsl'}}. (I hope there is a better way) Suggestions please.
db.survey.aggregate([
{ $match: {
image: { $elemMatch: {hsl: 1}}, // docs which have image.hsl
'dim.hsl': { $exists: true} // docs which have dim.hsl
}},
{ $redact : {
$cond: {
if: { $or : [
{$eq: ['$hsl',1]}, // for image array document with hsl:1
{$eq : ['$type' ,'article']},// for main document node
{$not : {$not : '$hsl'}} // for dim -- NOT WORKING
]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}}]);