如何在聚合函数之间添加 if 条件,假设我有一个来自请求"input"的参数,如果我有输入,我想看起来 id 大于该 id,如果我没有输入,我将不会匹配 id,我该如何实现?
collection.aggregate(
// Pipeline
[
// Stage 1
{
$match: {
"created_at": {$gte: fromDate, $lt: toDate},
"type": {$in : typeArray},
if (input){
"_id": {$gte: ObjectId("blahblahblah")}
}
}
},
{
$lookup: // Equality Match
{
from: "users",
localField: "some_id",
foreignField: "_id",
as: "user"
}
},
{
$sort:
{
"_id": 1
}
},
{
$limit: pageSize
}
])
你可以这样使用,对于 IF 条件
{ $cond: { if: (boolean-expression(, then: (true-case(, else: (假写( }}
或
{ $cond: [ (布尔表达式(, (真大小写(, (假大小写( ] }
有关参考,您可以查看文档
https://docs.mongodb.com/manual/reference/operator/aggregation/cond/