I have a list of documents in MongoDB with a tree structure. I want a single aggregation query which returns the count of all nested children, given an _id
property.
Structure:
{
'_id': '1',
'parentId': null,
},
{
'_id': '2',
'parentId': '1',
},
{
'_id': '3',
'parentId': '1',
},
{
'_id': '4',
'parentId': '3',
}
Aggregation result: (given: _id='1'
)
{
total_children: 3
}
I understand that this probably requires a $graphLookup
stage, and this question is very similar to Recursive search on a collection in MongoDB but is backwards in a sense.