Alexander
Alexander

Reputation: 871

Count Recursively on a collection in MongoDB

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.

Upvotes: 2

Views: 1057

Answers (1)

s7vr
s7vr

Reputation: 75984

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"}}}
])

Upvotes: 5

Related Questions