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}]}]}]}]

Query

db.collection.aggregate([{$addFields:{res:{$function:{body:"function drill(t, n) {if (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:{$arrayElemAt:["$res",0]},_id:0}},{$replaceRoot:{newRoot:"$res"}}])

Result