Mongo汇总计数子文档(对评论的计数答复)

问题描述 投票:0回答:1

我有一个名为comments的集合,其中的结构类似于:

{
  _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'
}

我想获得特定级别的评论,并添加每个评论的数量(parentSlug等于评论条目)。

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

我认为这对Mongo聚合是可行的,但不确定我需要哪些聚合阶段以及如何构建它们。

mongodb mongodb-query
1个回答
0
投票

您基本上在这里需要$graphLookup

$graphLookup

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

© www.soinside.com 2019 - 2024. All rights reserved.