我有一个名为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聚合是可行的,但不确定我需要哪些聚合阶段以及如何构建它们。
您基本上在这里需要$graphLookup
$graphLookup
db.collection.aggregate([
{ $graphLookup: {
from: "collection",
startWith: "$slug",
connectFromField: "slug",
connectToField: "parentSlug",
as: "replyCount",
maxDepth: 2,
depthField: "d"
}},
{ $addFields: {
replyCount: { $size: "$replyCount" }
}}
])