I want to write a MongoDB Aggregation Query to do the following:
- I pass a variable to the query method.
- If variable is not null, I want to check if it matches.
- 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!