title: How to add to an existing MongoDB Bson Filter in Java
body: <p>I'm using MongoDB 3.6.3 and the 3.6.0 Mongo &amp; Bson drivers for Java.</p>
  
  <p>Given the following filter:</p>
  
  <pre><code>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));
  </code></pre>
  
  <p>I need to conditionally add another field to <strong>filter</strong>, effectively making it:</p>
  
  <pre><code>   Bson filter = and(eq("field1", value),
                       gt("field2", value2),
                       eq("field3", optionalValue));
  </code></pre>
  
  <p>Is there a way to do this by appending that field to <strong>filter</strong>, or do I have to create the filters separately?  eg.</p>
  
  <pre><code>   Bson filter;
     if (optionFieldRequired)
     {
        Bson filter = and(eq("field1", value),
                          gt("field2", value2));
     }
     else
     {
        Bson filter = and(eq("field1", value),
                          gt("field2", value2),
                          eq("field3", optionalValue));
     }
  </code></pre>