mongodb - Mongodb - 从聚合查找中的子集合中计数
问题描述
我有以下有效的 mongo db 查询:
.collection('commentsPosts')
.aggregate(
[
{$match:{
commentedAt: {
$lte: from,
},
...(postId && { postId }),
}
},
{$lookup:
{
from:"users",
localField:"commentedBy",
foreignField:"_id",
as:"commenterDetails"
// NEED TO LOOK UP "posts" collection here to find number of posts by commenterDetails.userId = posterId in posts table
},
}
]
)
我需要再往下一层来查找帖子数量以查找帖子集合中commenterDetails.userId = posterId 的帖子数量
我正在寻找一种将下面的工作查询添加到上面的查询的方法。
const userPostCount = await req.db.collection('posts').countDocuments({
creatorId: userId,
});
解决方案
您可以像这样使用嵌套的 $lookups:https ://mongoplayground.net/p/_il8aiilLh5
db.comments.aggregate([
{$lookup:
{
from:"users",
let: {userId: "$commentedBy"},
as:"commenterDetails",
pipeline: [
{$match: {$expr: {
$eq: ["$$userId", "$_id"],
}}},
{$lookup: {
from: "posts",
as: "posts",
let: {posterId: "$_id"},
pipeline: [
{$match: {$expr: {
$eq: ["$posterId", "$$posterId"]
}}},
{$count: "total"},
]
}},
{$addFields: {
posts: {$arrayElemAt: ['$posts', 0]}
}},
]
},
},
{$addFields: {
commenterDetails: {$arrayElemAt: ['$commenterDetails', 0]}
}}
])
推荐阅读
- python - Python pandas:将数据框合并到系列索引和数据框列上的系列
- r - 将不同的日期和时间列合并为一列作为日期时间
- jquery - ajax 调用中不需要的 null 导致未找到错误
- c# - C# 服务器客户端在连接 UWP 时失败 (2)
- python - 升级过时的软件包后 pip 需要密码
- c++ - c++ r值引用应用于函数指针
- linux - 当 IP 地址改变时 TCP 套接字会发生什么?
- excel - 我需要帮助修复这个 VBA 宏
- r - Alternative to (m)get in data.table functions
- firebase - Difference between Firebase service account key files from Firebase and from GCloud?