Skip to content
Advertisement

Using the MongoDb Java drivers is there a way to get Filters function dynamically

ie., Filters.search(“eq”, “name”, “Smith”) does the same thing as Filters.eq(“name”, “smith”)

I’m writing some code that will search MongoDb depending on parameters passed in…

So currently, my ugly code looks like

if (param.equals("eq")) Filters.eq("name", name);
if (param.equals("gt")) Filters.gt("name", name); 
etc..

I’m hoping there is something like

Filters.search("gt", "name", name) ; 
Filters.search("eq", "name", name) ; 
etc...

Or perhaps there are other methods in the MongoDb java driver that can help.

I’ve looked through com.mongodb.client.model.Filters and com.mongodb.client.model.* but haven’t seen anything that seems promising.

Advertisement

Answer

I haven’t seen anything promising either. The mechanisms behind the Filters API seem to have been declared as private which seems to effectively close off any possibility of calling them directly or via subclassing.

If you desperate to do this, you could fork the MongoDB Java client code and modify the API so that you can inject operations directly. But I think your “clunky” approach is probably better.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement