如何在聚合管道中实现条件匹配阶段

How to implement a conditional match stage in the aggregate pipeline

我有一个这样的舞台

{
  $match: { isLive: true },
}

isAdmin的外部变量。

如果isAdmin我想绕过舞台
如果!isAdmin我要运行舞台

本质上就像一个短路运算符

{
  !isAdmin && $match: { isLive: true },
}

我尝试了多种运算符组合,但就是无法正常工作(我对 Mongo 还很陌生)。我敢肯定这很简单,但我就是想不通。

这样使用:

const pipeline = [];
if (!isAdmin) pipeline.push({ $match: { isLive: true } });
pipeline.push({ $project: { _id: 1 } });

db.collection.aggregate(pipeline)

您也可以使用其他 Array methods 来组成您的管道。

或尝试

{ $match: { $expr: { $or: [isAdmin, "$isLive"] } } }