Mongo db dynamic query

I created a dummy play model, where:

  • Persons have names
  • Persons have cars
  • Cars have names

I´m trying to do this query on the person collection:
"name": { $regex: {{ textInput1.value }} },
"" : { $regex: {{ textInput2.value }} }

So add search by person name and by car name... (semantics are a bit absurd, but you get the deal)...

If the textInput2.value == "", I do not want it in the query. If it has a value, I want it in, and doing as I have specified in the example query.

I cannot figure out how to deal with the case where its value == ""?

I can´t figure out the {{ textInput2.value? : }} construction to solve this, or a mongodb query contruct to deal with this??

Any help is appreciated.

Note: I believe a better way to deal with dynamic queries is just to have an normal input field as you have now, and then a "ran" field where I can just put some javascript to dynamically build the query, as I thing you got yourself in trouble with the "overlapping" syntax of your double brackets and mongo´s native notation of queries. But I think the product is good.

Ok, there you have it. Any help appreciated.


Hey @nick123, happy to help! :smiley:

I think a ternary would be perfect for you use case. The construction would look like this: {{ textInput2.value ? textInput2.value : '' }} which asks, if there is an input2 value, return it, else return an empty string.

Please try this and let me know if it helps!


The ternary does not work. Because I need:

  1. When textInput2.value is empty:
    "name": { $regex: {{ textInput1.value }} }
  2. When textInput2.value is not empty:
    "name": { $regex: {{ textInput1.value }} },
    "" : { $regex: {{ textInput2.value }} }

So the property "" only is present in query when textInput2.value is not empty.

Plz advice,

Hi @nick123! Have you tried using undefined to remove key if there is no value? We have some docs on dynamically adding properties to an object here.

Let me know if this helps!