Skip to content
Advertisement

How to add to an existing MongoDB Bson Filter in Java

I’m using MongoDB 3.6.3 and the 3.6.0 Mongo & Bson drivers for Java.

Given the following filter:

JavaScript

I need to conditionally add another field to filter, effectively making it:

JavaScript

Is there a way to do this by appending that field to filter, or do I have to create the filters separately? eg.

JavaScript

Advertisement

Answer

Filters.and() returns an instance of the private static class: Filters.AndFilter. There is no public method on AndFilter allowing you to change its state. So, if you want to append an additional filter after constructing this object you’ll have to convert it into some other, mutable, form. For example; a BsonDocument.

The following code creates two BsonDocument instances, one by adding a filter to an existing set of filters and the other by creating all three filters at once. Both of these BsonDocument instances are identical and can be used in collection.find():

JavaScript

So, this solution is functional but I think it’s harder to understand and less standard than wrapping the create call in a conditional block, like in your question …

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