gpt4 book ai didi

node.js - MongoDB 统计相关文档的最佳实践

转载 作者:行者123 更新时间:2023-12-04 21:57:55 27 4
gpt4 key购买 nike

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

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

如果可能,我想使用 MongoDB 聚合方式(如果这是最好的方式)我知道如何使用单独的方法 .count() 和 .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 进行计数。

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

关于node.js - MongoDB 统计相关文档的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48389112/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com