Home > Blockchain >  How to implement a conditional match stage in the aggregate pipeline
How to implement a conditional match stage in the aggregate pipeline

Time:03-17

I have a stage which looks like this

{
  $match: { isLive: true },
}

and an external variable of isAdmin.

If isAdmin I want to bypass the stage.
If !isAdmin I want to run the stage.

Essentially like a short-circuit operator

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

I've tried many combinations of operators but I just can't get it to work (I'm very new to Mongo). I'm sure it's very simple but I just can't figure it out.

CodePudding user response:

Use it like this:

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

db.collection.aggregate(pipeline)

You may use also other Array methods to compose your pipeline.

Or try

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