MongoDB Match Aggregation If Variable is Not Null

Viewed 20

I want to write a MongoDB Aggregation Query to do the following:

  1. I pass a variable to the query method.
  2. If variable is not null, I want to check if it matches.
  3. If the variable is null, no match is required

For example: I pass companyName as a variable and if the name is not null, I get records for that company name and if the variable is null, I get records for all company names.

I have come up with something like this: (The match is a part of a larger Aggregation query)

 { $match : { $and: [ { ?0: { $ne : null }} , {'companyName' : ?0}] }} <br>
 List<AggregationGroupSum> getCountByCompany(String companyName)

The ?0 is the variable companyName

I understand that the approach to check it is quite juvenile, but I am new to MongoDB and aggregation queries and I would like any help on how to tackle this, whether it be through the aggregation or otherwise.

Thanks!

1 Answers

You should use the $or operator instead of $and.

This will fulfill:

  1. If ?0 is null, the document is selected.

  2. If ?0 is matched with companyName value, the document is selected.

{
  $match: {
    $expr: {
      $or: [
        { $eq: [?0, null] },
        { $eq: ["$companyName", ?0] }
      ]
    }
  }
}

Related