khateeb
khateeb

Reputation: 5469

How to add a MongoDB match argument if it comes from frontend and not add any argument if it doesn't?

I am creating an aggregation in MongoDB using NodeJS. When the resolver function is called with an argument, I want it to be added to MongoDB match function and if it doesn't exist, then there will be no addition. The problem I am facing is that if there is no addition, no results are coming and if there is addition then the query is not coming properly. It is coming like this: phaseMatch = 'phase': { $in: CAT,MOD }. how do I make it come like phaseMatch = 'phase': { $in: ['CAT','MOD'] }? Is there any way to do this conditional only in the MongoDB aggregation and not use any JS?

async WeeklyTable(_, { batchSize, phase }) {
    let res = [];
    let phaseMatch = "";
    if(phase) phaseMatch = "'phase': { $in: " + phase + " }";
    return await collection.aggregate([{ 
        $match: {
            "segment": { 
                $exists: true, 
                $ne: null 
            },
            phaseMatch
        }    
    }];
}

Upvotes: 1

Views: 38

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

There are many ways to dynamically build a query condition, here is a quick example:

async WeeklyTable(_, { batchSize, phase }) {
    const res = [];
    const matchCond = {
        "segment": {
            $exists: true,
            $ne: null
        },
    }
    if(phase) {
        matchCond.phase = {$in: phase}
    };
    return await collection.aggregate([{
        $match: matchCond
    }];
}

Not sure exactly what you're trying to do with creating it as a string, the Mongo driver doesn't parse string arguments as query conditions.

EDIT

Without any javascript you could do:

db.collection.aggregate([
  {
    $match: {
      "segment": {
        $exists: true,
        $ne: null
      },
      $expr: {
        "$setIsSubset": [
          [
            "$phase"
          ],
          {
            $ifNull: [
              phase,
              [
                "$phase"
              ]
            ]
          }
        ]
      }
    }
  }
])

Upvotes: 1

Related Questions