Complex filter queries

Hi,

I´ve 9 input elements and i have no idea how to start to make a filter with every possible combination. The problem: I don´t want to write 512 mongo queries. Has anybody else done something like this or can give me a starting point?

thanks

1 Like

combine the values of the input into an array and use the $in mongo selector

thanks, but that doesn´t solve the problem of multiple combinations.

For example with only 4 combinations = 16

a= false
x = false
y = false
z = false

a= true
x = false
y = false
z = false

a= true
x = true
y = false
z = false

a= true
x = true
y = true
z = false

a = true
x = true
y = true
z = true

a= false
x = true
y = true
z = true

a= false
x = false
y = true
z = true

a= true
x = false
y = true
z = true

a= true
x = true
y = false
z = true

a= true
x = true
y = true
z = false

a= false
x = true
y = false
z = false

a= false
x = false
y = true
z = false

a= false
x = true
y = true
z = false

a= true
x = false
y = false
z = true

what do you mean by true/false and axyz? can you give an example to what a few of those inputs would be and an example to what you would be querying for?

I take it there is no one general answer to your question. so an example to your specific use case would help us help you.

I’m not sure why you’d need to/want to define a query for each permutation of input value. Use variables to build the query, taking the appropriate precautions.

simple example. status and position are selects where multiple elements can be combined.

after click on search button:

if (
    position == null    &&
    status   != null
    ) 
      {
	Pages.set("filters", {'status': { $in: status } });
      };

if (
    position != null    &&
    status == null
    )
      {
        Pages.set("filters", {'position': { $in: position } });
					
      };

if (
    position != null    &&
    status   != null
    )
    {
	Pages.set("filters",{ 
		         'position': { $in: position}, 
			 'status':{ $in: status } 
		 });
    }

This can get a lot more complicated with 9 fields. Perhaps the solution is dead simple, but i don’t see it.

Have a close look at the answer to this question. I don’t know if all of the details are the same, but these kinds of problems can be built in parts rather than iterating through every combination of inputs.

1 Like

@dweldon seems to have beaten me to it.

You’ll just need to build the query based on the key, starting with an empty query = {} object and populating it using a pattern of query[filterKey] = {$in: filterValue}

1 Like

Thank you very much. When you see it, it looks so logical to do.