Tobias
Tobias

Reputation: 344

Mongo Aggregation Count Child Documents (Count Replies For Comments)

I have a collection called comments where the structure is something like:

{
  _id: ObjectId(),
  slug: 'foo',
  text: 'I am a comment'
}, 
{
  _id: ObjectId(),
  slug: 'foo/bar',
  parentSlug: 'foo',
  text: 'I am a reply'
},
{
  _id: ObjectId(),
  slug: 'foo/bar/baz',
  parentSlug: 'foo/bar',
  text: 'I am a reply to a reply'
}

I want to get the comments for a certain level and add the number of replies to each (where parentSlug is equal to the comment slug).

{
  _id: ObjectId(),
  slug: 'foo',
  text: 'I am a comment',
  replyCount: 1
}

I think this is possible with Mongo aggregation but am not sure what aggregation stages I need and how they would be structured.

Upvotes: 1

Views: 129

Answers (1)

Ashh
Ashh

Reputation: 46491

You basically need $graphLookup here

db.collection.aggregate([
  { $graphLookup: {
    from: "collection",
    startWith: "$slug",
    connectFromField: "slug",
    connectToField: "parentSlug",
    as: "replyCount",
    maxDepth: 2,
    depthField: "d"
  }},
  { $addFields: {
    replyCount: { $size: "$replyCount" }
  }}
])

MongoPlayground

Upvotes: 1

Related Questions