我正在从评论表中提取数据,并且可以正常工作。我想在users
集合上进行兼顾性能的联接,以获取有关发表评论的用户的详细信息。
这是我使用Next js的代码。我添加了聚合/查找,现在什么也没回来。
const from = req.query.from ? new Date(req.query.from) : new Date();
const postId = req.query.by;
const comments = await req.db
.collection('commentsPosts')
.find({
commentedAt: {
$lte: from,
},
...(postId && { postId }),
})
.sort({ commentedAt: -1 })
.limit(parseInt(req.query.limit, 10) || 10)
//This part is not working and breaking the whole query
.aggregate({
$lookup:{
from:"users",
localField:"createdBy",
foreignField:"_id",
as:"commenterDetails"
}
})
/////////////
.toArray();
res.send({ comments });
编辑
根据下面的答案进行了更新,但仍然没有结果
.collection('commentsPosts')
.aggregate(
[
{$match:{
commentedAt: {
$lte: from,
},
...(postId && { postId }),
}
.sort({ commentedAt: -1 })
.limit(parseInt(req.query.limit, 10) || 10)
},
{$lookup:
{
from:"users",
localField:"createdBy",
foreignField:"_id",
as:"commenterDetails"
}
}
]
).toArray();
答案 0 :(得分:4)
当您计划使用 aggregate()
时,无需执行 find()删除 find(),并在集合管道中引入 $ match 。
db.comments.aggregate(
[
{$match:{commentedAt:{$gt:QUERY_CLAUSE_HERE}},
{$lookup:{...}}
]
)