MongoDB计算相关文档的最佳实践 [英] MongoDB best practice to count related documents

查看:55
本文介绍了MongoDB计算相关文档的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering what is the best practice to get a count of related documents of a particular document in MongoDB.

方案如下: 我需要获取用户共享的帖子,也需要获取与这些帖子相关的评论总数.

Scenario is as follows: I need to get posts that users shared and I need to get total number of comments related to those posts as well.

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

I would like to use the MongoDB Aggregation way if possible (if that is the best way of doing it) I am aware how to perform this query using separate methods .count() and .find().

帖子集合中的文档:

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

评论集中的文档

{
    _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即可对返回的评论加上$size来提取每个帖子的评论,以计数.

You can just do a $lookup to pull the posted comments for each post with $size on the returned comments for a count.

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

这篇关于MongoDB计算相关文档的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆