javascript - MongoDB聚合查找不适用于多个参数
问题描述
我正在从评论表中提取数据并且它有效。我想在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:{...}}
]
)
推荐阅读
- c# - 从名称列表中绘制项目
- javascript - Chart.js 如何更改 y 轴标题位置
- python - Python 3 小数精度
- linux - 在 Linux 中,两个具有相同优先级的 SCHED_FIFO 任务是否在每个周期内获得处理时间?
- php - 如何在一个php页面上添加两个mysql查询的结果?
- java - 如何在子类中覆盖和使用父类方法
- python - 允许用户下载在 AWS 上生成的 zip 文件
- laravel - Laravel 和 GraphQL:使用 laravel-graphql 时如何使用 Laravel 的 Passport 进行身份验证?
- php - PHP - 按子数组中的值对数组进行排序 - DESC 和 ASC
- regex - 查找包含超过 3 个数字的行(正则表达式)