MongoDB best practice to count related documents

淺唱寂寞╮ 提交于 2020-01-05 04:08:01

问题


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.

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().

document in posts collection:

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

document in comments collection

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

Desired Result:

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

回答1:


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" } } }]
)


来源:https://stackoverflow.com/questions/48389112/mongodb-best-practice-to-count-related-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!