MongoDB统计相关文档的最佳实践

Pet*_*lak 3 mongoose mongodb node.js aggregation-framework

我想知道在 MongoDB 中获取特定文档的相关文档计数的最佳实践是什么。

场景如下:我需要获取用户分享的帖子,我还需要获取与这些帖子相关的评论总数。

如果可能,我想使用 MongoDB 聚合方式(如果这是最好的方式)我知道如何使用单独的方法 .count() 和 .find() 执行此查询。

帖子集合中的文档:

{
    _id: ObjectId('5a66321e7e2043078bc3b88a'),
    uid: 'UniqueIDofTheUser',
    text: 'Post text'
}
Run Code Online (Sandbox Code Playgroud)

评论集合中的文档

{
    _id: ObjectId('5a66321e7e2043078bc3b88c'),
    uid: 'UniqueIDofTheUser',
    post_id: ObjectId('5a66321e7e2043078bc3b88a'),
    text: 'Comment text'
}
Run Code Online (Sandbox Code Playgroud)

预期结果:

[
    {
        _id: ObjectId('5a66321e7e2043078bc3b88a'),
        uid: 'UniqueIDofTheUser',
        text: 'Post text',
        commentsCount: 20
    },
    {
        _id: ObjectId('5a66321e7e2043078bc3b88c'),
        uid: 'UniqueIDofTheUser',
        text: 'Another post',
        commentsCount: 3
    },
    {
        _id: ObjectId('5a6632e17e2043078bc3b88f'),
        uid: 'UniqueIDofTheUser',
        text: 'Some random post',
        commentsCount: 4
    },
]
Run Code Online (Sandbox Code Playgroud)

use*_*814 8

您可以只$lookup对每个帖子的已发布评论进行拉取$size,并对返回的评论进行计数。

db.posts.aggregate(
 [{ $lookup: { 
    from: "comments", 
    localField: "_id", 
    foreignField: "post_id", 
    as: "commentsCount" 
 } }, 
 { $addFields: { "commentsCount": { $size: "$commentsCount" } } }]
)
Run Code Online (Sandbox Code Playgroud)