Kevin Day
Kevin Day

Reputation: 16413

MongoDB Java driver Filters.expr produces incorrect filter expression

I am trying to build a filter expression that looks like this:

{ $expr:{ $gt:['$bal1', '$bal2'] } }

using the Filter.expr function:

Bson filter = Filters.expr( gt("$bal1", "$bal2") );
BsonDocument doc = filter.toBsonDocument(BsonDocument.class, collection.getCodecRegistry());
System.out.println(doc.toJson());

this produces the following json:

{ "$expr" : { "$bal1" : { "$gt" : "$bal2" } } }

Clearly that's not right. Is there some way of creating this query using Java static import interfaces, or am I stuck having to construct strings manually? I'm new to Mongo, and I can't imagine that everyone is building strings by hand - any guidance would be greatly appreciated.

MongoDB Java driver 3.6.1

Upvotes: 1

Views: 3203

Answers (1)

s7vr
s7vr

Reputation: 75994

$expr takes aggregation comparison functions. So you can't use the regular query builder.

Unfortunately, you just have to use Document.parse to parse the aggregation comparison string.

Bson filter = Filters.expr( Document.parse(" { $gt: [ \"$bal1\" , \"$bal2\"] } ") );

Compare query operators vs aggregation comparison operators.

Check the implementation jira for more details.

Upvotes: 8

Related Questions