I have a query in MongoDB like so
collection.find(
{$and:[
{origin:{ $in: countries }}, {brand: {$in: brands}}
]}
).toArray();
If both the arrays countries
and brands
have some values, the query will correctly return documents that have both the specified country and brand. However, if one of these arrays is empty, the query will no longer work. How can I fix this? I want my users to be able to search only by country or only by brand, not always by both. I also have other parameters which should be searchable independently or combined with other parameters. How can I construct a query that will give me the desired output?
3
Answers
Did you try changing to $or?
Try this:
Simply verification that first element of both array exists.
In the example above I used ephemeral object
userRequest
to illustrate object with inputs for filtering. The main idea is that you have the generalquery
object with$and
array for all the conditions inside (but you may modify thequery
object as well). Then if user specified some filters – you just need to add corresponding condition to the conditions array.