Database
[{"name":"parent-a","status":{"state":"good"},"children":["child-1","child-2"]},{"name":"child-1","state":"good","parent":"parent-a"},{"name":"child-2","state":{},"parent":"parent-a"},{"name":"parent-b","status":{"state":"good"},"children":["child-3","child-4"]},{"name":"child-3","state":"good","parent":"parent-b"},{"name":"child-4","state":"bad","parent":"parent-b"},{"name":"parent-c","status":{"state":"bad"},"children":["child-5","child-6"]},{"name":"child-5","state":"good","parent":"parent-c"},{"name":"child-6","state":"bad","parent":"parent-c"}]
Query
db.collection.aggregate([{$match:{$or:[{$and:[{"status.state":"good"},{parent:{$exists:false}},{"children.0":{$exists:true}}]},{$and:[{"state":{$in:["bad",null,{}]}},{parent:{$exists:true}}]}]}},{$unwind:{path:"$children",preserveNullAndEmptyArrays:true}},{$addFields:{isParent:{$cond:[{$eq:[null,{$ifNull:["$parent",null]}]},1,0]}}},{$group:{_id:{$cond:["$isParent","$children","$name"]},hasParnet:{$sum:"$isParent"},hasChild:{$sum:{$subtract:[1,"$isParent"]}},state:{"$mergeObjects":{$cond:["$isParent",{},{state:"$state"}]}}}},{$match:{hasChild:{$gt:0},hasParnet:{$gt:0}}},{$group:{_id:null,children:{$push:{name:"$_id",state:"$state.state"}}}}])