Database
[{"_id":"123","someKey":"blue","children":[{"foo":"bar","anotherKey":"anotherValue","whateverA":111}]},{"_id":"456","blahKey":"dog","children":[{"anotherRandom":"randomValue","children":[{"moreRandom":"stuffValue","children":[{"foo":"bar","animalKey":"legsValue","whateverB":222}]}]}]},{"_id":"127","someKey":"green","children":[{"faa":"bar","anotherKey":"anotherValue","whateverA":111}]},]
Query
db.collection.aggregate([{$addFields:{res:{$function:{body:"function drill(t, n) {if (n && n.length > 0){for (let elem of n){if(elem['foo'] && elem['foo'] === 'bar'){t.push(elem);}else {drill(t, elem.children)}}}return t}",args:[[],"$children"],lang:"js"}}}},{$project:{res:{$cond:[{$gt:[{$size:"$res"},0]},{$arrayElemAt:["$res",0]},null]},_id:0}},{$match:{"res":{$ne:null}}},{$replaceRoot:{newRoot:"$res"}}])