Java Mongo Filter equality checks

24 views
Skip to first unread message

Albert Kam

unread,
Aug 11, 2017, 12:44:23 PM8/11/17
to mongodb-user
I'm currently involved with testing dynamically generated query filters.
It seems that the filters havent provided an implementation for equality check.

Therefore, this test will fail:

// does not pass
@Test
public void testFilterEqualityByFilterType() {
assertEquals(and(eq("hello", "world")), and(eq("hello", "world")));
}


But this does pass:
@Test
public void testFilterEqualityByString() {
assertEquals(and(eq("hello", "world")).toString(),
and(eq("hello", "world")).toString());
}

As a tester, i'd be more comfortable checking on equality rather than string.
Hopefully this could serve as a good input for future improvements.

Thank you guys for developing such great products.

Jeff Yemin

unread,
Sep 4, 2017, 1:29:17 PM9/4/17
to mongodb-user
The Filters API returns instances of the Bson interface, which are not reliably comparable for equality without providing an encoder for the values.  But you can easily do this via the Bson.toBsonDocument method.  Just pass the Bson instances to this helper method before comparing for equality:

   BsonDocument toBsonDocument(Bson bson) {
     
return bson.toBsonDocument(BsonDocument.class,
             
MongoClient.getDefaultCodecRegistry());  // or use a custom CodecRegistry instance
   
}

      // passes now
   @Test
   public void testFilterEqualityByFilterType() {
      assertEquals
(toBsonDocument(and(eq("hello", "world"))), toBsonDocument(and(eq("hello", "world"))));
   
}
Reply all
Reply to author
Forward
0 new messages