db.collection.aggregate([
{
$match: {
tags: "b", // add your search
childs: { $ne: [] }
}
},
{
$lookup: {
from: "collection",
let: { childs: "$childs" },
as: "ids",
pipeline: [
{
$match: {
$expr: { $in: ["$id", "$$childs"] },
tags: { $ne: "b" } // add your search
}
}
]
}
},
{
$project: {
id: 1,
ids: {
$reduce: {
input: "$ids",
initialValue: [],
in: { $concatArrays: ["$$value", ["$$this.id"]] }
}
}
}
}
])