Consider the structure like this:
class Group {
_id: ObjectId
subGroups: ObjectId[]
name: string
info: string
}
A document for Group A in the database should be...
_id: ObjectId("6092387f9c69970c20fe648a")
subGroups: [
ObjectId("6092387f9c69970c20fe648b"), // Group B
ObjectId("6092387f9c69970c20fe648c"), // Group C
],
name: "Group A",
info: "..."
How can I query in the mongodb to get all children including itself?
For example,
Query for A: Output A, B, C, D, E, F, G, H, I, J
Query for B: Output D, E
What you want to use is called $graphLookup, it recursively iterates until no more matches are found, like so:
db.collection.aggregate([
{
$match: {
"name": "Group A"
}
},
{
$graphLookup: {
from: "collection",
startWith: "$subGroups",
connectFromField: "subGroups",
connectToField: "_id",
as: "groupHierarchy",
}
},
{
$project: {
result: {
"$concatArrays": [
[
"$name"
],
{
$map: {
input: "$groupHierarchy",
as: "group",
in: "$$group.name"
}
}
]
}
}
}
])