I'm using MongoDB 3.6.3 and the 3.6.0 Mongo & Bson drivers for Java.
Given the following filter:
import static com.mongodb.client.model.Filter.and;
import static com.mongodb.client.model.Filter.eq;
import static com.mongodb.client.model.Filter.gt;
.
.
.
Bson filter = and(eq("field1", value),
gt("field2", value2));
I need to conditionally add another field to filter, effectively making it:
Bson filter = and(eq("field1", value),
gt("field2", value2),
eq("field3", optionalValue));
Is there a way to do this by appending that field to filter, or do I have to create the filters separately? eg.
Bson filter;
if (optionFieldRequired)
{
filter = and(eq("field1", value),
gt("field2", value2));
}
else
{
filter = and(eq("field1", value),
gt("field2", value2),
eq("field3", optionalValue));
}