Home:ALL Converter>Count Recursively on a collection in MongoDB

Count Recursively on a collection in MongoDB

Ask Time:2018-01-24T07:33:50         Author:Alexander

Json Formatter

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.

Author:Alexander,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48412571/count-recursively-on-a-collection-in-mongodb
yy