[英]MongoDB best practice to count related documents
I was wondering what is the best practice to get a count of related documents of a particular document in MongoDB. 我想知道在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(). 我想在可能的情况下使用MongoDB聚合方式(如果这样做是最好的方式),我知道如何使用单独的方法.count()和.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
},
]
You can just do a $lookup
to pull the posted comments for each post with $size
on the returned comments for a count. 您只需执行$lookup
即可将每个帖子的已发布评论与返回的评论上的$size
进行计数。
db.posts.aggregate(
[{ $lookup: {
from: "comments",
localField: "_id",
foreignField: "post_id",
as: "commentsCount"
} },
{ $addFields: { "commentsCount": { $size: "$commentsCount" } } }]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.