Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregation - Match input parameter if provided else do not match

I have a MongoDB aggregation query in which I have the following:

{ $match: { version: versionNumber }

The 'versionNumber' is an optional input parameter to the aggreagation. If this versionNumber is not provided, then I do not want this match to be performed.

Currently, if the versionNumber is not supplied, the match still happens and I get a blank query output.

Is there a way in Mongo to do this? Thanks!

like image 983
Rakesh Mhasawade Avatar asked Sep 19 '25 22:09

Rakesh Mhasawade


2 Answers

I am not sure what will be the value in versionNumber when its not provided (optional), lets assume versionNumber will be any from "" or undefined or null,

  • if versionNumebr is not available then it will skip and when its available then it will match $eq condition
  • you can add more values in array [null, "", "undefined"], 0 zero or anything you wanted to skip
  {
    $match: {
      $expr: {
        $cond: [
          { $in: [versionNumber, [null, "", "undefined"]] },
          true,
          { $eq: ["$version", versionNumber] }
        ]
      }
    }
  }
  • if versionNumebr will be always single possible value "" then you can use $eq instead of $in,
  {
    $match: {
      $expr: {
        $cond: [
          { $eq: [versionNumber, ""] },
          true,
          { $eq: ["$version", versionNumber] }
        ]
      }
    }
  }

Playground

like image 136
turivishal Avatar answered Sep 22 '25 22:09

turivishal


There is a way to do that, yes, but it should be done in the application code. When building the pipeline array to pass to the query, only include the $match stage if the necessary information is provided.

var pipeline=[]
if (versionNumber) pipeline.push( {$match: {version: versionNumber }} )
pipeline.push( ... Other Stages ... )

db.collection.aggregate(pipeline)
like image 29
Joe Avatar answered Sep 23 '25 00:09

Joe