[JAVA-4051] BasicDBObject.equals throws exception when one of its fields is a UUID Created: 16/Mar/21  Updated: 28/Oct/23  Resolved: 19/Mar/21

Status: Closed
Project: Java Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: 4.2.3

Type: Bug Priority: Major - P3
Reporter: Jeffrey Yemin Assignee: Jeffrey Yemin
Resolution: Fixed Votes: 2
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to JAVA-4140 BasicDBObject/Document toString metho... Closed

 Description   

Consider this code:

      var uuid = UUID.randomUUID()
      var dbo1 = new BasicDBObject("_id", uuid);
      var dbo2 = new BasicDBObject("_id", uuid)
 
      boolean equal = dbo1.equals(dbo2)

In the 3.x driver equal will be true, but in 4.x it will throw:

Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: 
The uuidRepresentation has not been specified, so the UUID cannot be encoded.
	at org.bson.codecs.UuidCodec.encode(UuidCodec.java:72)
	at org.bson.codecs.UuidCodec.encode(UuidCodec.java:37)
	at org.bson.codecs.EncoderContext.encodeWithChildContext(EncoderContext.java:91)
	at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:246)
	at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:159)
	at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:67)
	at com.mongodb.BasicDBObject.toBson(BasicDBObject.java:225)
	at com.mongodb.BasicDBObject.equals(BasicDBObject.java:215)

This is a breaking change. I think we can get around it though, because in the case of equality we don't really care what uuid representation is used, since we are only using its encoded form to test equality and then throw it away.

Known workarounds:

  • Use the org.bson.Document class, which has a more straightforward equals method that does not attempt to encode any values
  • Manually convert UUID to BsonBinary, e.g. BsonBinary(UUID.randomUUID(), UuidRepresentation.JAVA_LEGACY)

Both are pretty invasive changes, though.

This issue was originally reported in the Community Forums at https://developer.mongodb.com/community/forums/t/issue-with-uuid-after-upgrading-to-4-2-1-for-java-client/98519.



 Comments   
Comment by Githook User [ 19/Mar/21 ]

Author:

{'name': 'Jeff Yemin', 'email': 'jeff.yemin@mongodb.com', 'username': 'jyemin'}

Message: Ensure BasicDBObject equals/hashCode works with UUID values (#688)

JAVA-4051
Branch: 4.2.x
https://github.com/mongodb/mongo-java-driver/commit/c5886fb7730de8dfd3926e32d48854c9d2b26800

Comment by Githook User [ 19/Mar/21 ]

Author:

{'name': 'Jeff Yemin', 'email': 'jeff.yemin@mongodb.com', 'username': 'jyemin'}

Message: Ensure BasicDBObject equals/hashCode works with UUID values (#688)

JAVA-4051
Branch: master
https://github.com/mongodb/mongo-java-driver/commit/a24ecdf5cdb945c0e51af3455fc7adcfc290d727

Generated at Thu Feb 08 09:01:07 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.