I’m trying to make a MongoDB query based on 3 optional filters taken from 3 fields.
Since these parameters are optional, one of the filters may not be set. So I can’t make a fixed query like this:
$result = $collection->find([ "Vara" => "Option1", "Assunto" => "Option2", "Resultado" => "Option3" ])
I had the idea to store the field entries into a PHP variable and just insert it into the find function.
When I get the field content via POST, I parse it into a variable like this:
$filter1 = ' "Vara" => " '.$_POST['field1'].' " '; //e.g. user wrote 'Option1' in the field.
If the user didn’t specify a filter in the field the variable is set as empty:
$filter2 = '';
So when I concatenate all the variables I get only the set filters:
$query = $filter1 . $filter2; //Prints: "Vara" => "Option1",
Then I would do this:
$result = $collection->find([ $query ])
But this didn’t work. I checked and $query is correct, I get no errors.
I know a possible solution would be using $regex. If the user didn’t set a filter I change it to " .* "
$result = $collection->find([ "Vara" => ['$regex' => " $field1 "], "Assunto" => ['$regex' => " $field2 "], "Resultado" => ['$regex' => " $field3 "] ])
But is there a better solution than doing
$regex => .* ?