Home > OS >  Perform match if parameter is present in MongoAggregation
Perform match if parameter is present in MongoAggregation

Time:02-12

I have a aggregation pipeline where i'd like to perform a match only if the intended params is present. For example;

params = { fruit: 'apple', other_params.. }

In my aggregation pipeline:

Some.collection.aggregate([ { "$match": { fruit: 'apple' } } ...other stages ])

So I'd like to run match stage only if i have fruit in params. can it be done?

CodePudding user response:

You can realize this via simple $or logic in the match stage:

db.collection.aggregate([
 {
  $match: {
   $or: [
    {
      fruit: {
        $exists: true,
        $eq: "apple"
      }
    },
    {
      fruit: {
        $exists: false
      }
    }
  ]
 }
}
])

explained:

  1. If the key fruit exist it will check if is equal to "apple"
  2. If the key do not exist it will not do anything

playground

CodePudding user response:

Mongodb queries are javascript objects, so you can construct them easy and dynamically, with code, based on the params you got. For example i think you need something like

params = { fruit: 'apple', other_params.. }
Some.collection.aggregate([ { "$match": params } ...other stages ])

If you want some of the params to be on the match, start with an empty {} and add the parameters that have to be in the $match.

  • Related