<p>使用<a href="https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/" rel="nofollow noreferrer">Aggregation Pipeline</a>我们可以得到期望的结果</p>
<p>下面的查询使用管道阶段<a href="https://docs.mongodb.com/manual/reference/operator/aggregation/project/" rel="nofollow noreferrer">$project</a>、<a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/" rel="nofollow noreferrer">$unwind</a>和管道操作符<a href="https://docs.mongodb.com/manual/reference/operator/aggregation/size/" rel="nofollow noreferrer">$size</a>和<a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sum/" rel="nofollow noreferrer">$sum</a></p>
<pre><code>db.collection_name.aggregate([
{ $project: {
"post_body": 1,
"author": 1,
"comments":1,
"comments_size":{$size: "$comments" }
}
},
{ $unwind: "$comments" },
{ $project: {
"post_body": 1,
"author": 1,
"comments":1,
"comments_size":1,
"replies_size" : {$size: "$comments.replies"}
}
},
{ $project: {
"_id":0,
"post_body": 1,
"author": 1,
"comments_count":{$sum:["$comments_size", "$replies_size"]}
}
}
])
</code></pre>
<p>聚合查询的第一部分使用$project,我们只是将所需的属性投影到下一个阶段,还将查找注释数组的大小。注释数组的大小存储在临时属性<code>comments_size</code></p>
<p>第二部分使用$unwind来断开<code>comments</code>和<code>comments.replies</code>中的嵌套数组,<code>comments</code>数组被解除,而<code>comments.replies</code>数组保持不变</p>
<p>第三部分使用$project查找回复的大小,并将其存储在临时属性<code>replies_size</code></p>
<p>第四部分也是最后一部分再次使用$project和<code>comments_size</code>和<code>replies_size</code>的$sum来获得所需的结果</p>