【问题标题】:MongoDB best practice to count related documentsMongoDB 统计相关文档的最佳实践
【发布时间】:2018-07-01 12:41:19
【问题描述】:

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

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

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

帖子集合中的文档:

{
    _id: ObjectId('5a66321e7e2043078bc3b88a'),
    uid: 'UniqueIDofTheUser',
    text: 'Post text'
}

cmets 集合中的文档

{
    _id: ObjectId('5a66321e7e2043078bc3b88c'),
    uid: 'UniqueIDofTheUser',
    post_id: ObjectId('5a66321e7e2043078bc3b88a'),
    text: 'Comment text'
}

期望的结果:

[
    {
        _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
    },
]

【问题讨论】:

  • 您可以使用$lookup 来为每个帖子提取已发布的 cmets,并在返回的 cmets 上使用 $size 进行计数。类似db.posts.aggregate([{ $lookup: { from: "comments", localField: "_id", foreignField: "post_id", as: "commentsCount" } }, { $addFields: { "commentsCount": { $size: "$commentsCount" } } }])
  • 嗨@Veeram,你拯救了我的一天。太感谢了!我会将此标记为正确答案,除非有另一个答案合理地描述了为什么要以另一种方式做。

标签: node.js mongodb mongoose aggregation-framework


【解决方案1】:

您可以使用$lookup 来提取每个帖子的已发布 cmets,并在返回的 cmets 上使用 $size 进行计数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2012-04-28
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多