2

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.

Alexander
  • 841
  • 1
  • 9
  • 23

1 Answers1

4

You can use below aggregation query.

Recursive lookup to locate all the children for a given _id followed by $size to count the chidren.

db.col.aggregate([
  {"$match":{"_id":"1"}},
  {"$graphLookup":{
    "from":col,
    "startWith":"$_id",
    "connectFromField":"_id",
    "connectToField":"parentId",
    "as":"children"
  }},
  {"$project":{"total_children":{"$size":"$children"}}}
])
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • This might be a dumb question, but what is `col` in the $graphLookup stage? edit: nevermind, that is my collection. Thank you! – Alexander Jan 24 '18 at 16:25