I have a below mongo collection "test" which does not have "tags" field on top level of the document.
{
"_id" : 1,
"title" : "123 Department Report",
"year" : 2014,
"subsections" : [
{
"subtitle" : "Section 1: Overview",
"tags" : "SI",
"content" : "Section 1: This is the content of section 1."
},
{
"subtitle" : "Section 2: Analysis",
"tags" : "STLW",
"content" : "Section 2: This is the content of section 2."
},
{
"subtitle" : "Section 3: Budgeting",
"tags" : "TK",
"content" : {
"text" : "Section 3: This is the content of section3.",
"tags" : "HCS"
}
}
]
}
My requirement is to select subsections having only "tags" value "STLW". I am running following aggregation query.
db.test.aggregate([
{ $redact: {
$cond: {
if: { $or: [ {$ifNull: ['$tags', true]}, {$eq: [ "$tags" , 'STLW' ]} ] },
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
However on running query I am getting all the sub documents in the below output:
{
"_id" : 1,
"title" : "123 Department Report",
"year" : 2014,
"subsections" : [
{
"subtitle" : "Section 1: Overview",
"tags" : "SI",
"content" : "Section 1: This is the content of section 1."
},
{
"subtitle" : "Section 2: Analysis",
"tags" : "STLW",
"content" : "Section 2: This is the content of section 2."
},
{
"subtitle" : "Section 3: Budgeting",
"tags" : "TK",
"content" : {
"text" : "Section 3: This is the content of section3.",
"tags" : "HCS"
}
}
]
}
However, I want the below output.
{
"_id" : 1,
"title" : "123 Department Report",
"year" : 2014,
"subsections" :
{
"subtitle" : "Section 2: Analysis",
"tags" : "STLW",
"content" : "Section 2: This is the content of section 2."
}
}
Can any one help me in achieving this ?
thanks...........