[英]MongoDB aggregate lookup not working with multiple parameters
我正在从评论表中提取数据并且它有效。 我想在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();
当您计划使用aggregate( ) 时,您不需要执行find( )
删除find()并在聚合管道中引入$match 。
db.comments.aggregate(
[
{$match:{commentedAt:{$gt:QUERY_CLAUSE_HERE}},
{$lookup:{...}}
]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.