MongoDB UUID problems in Java drivers
October 4, 2026 · 15 min read
Java services are a frequent source of MongoDB UUID bugs: documents look fine in Compass but findById returns empty, aggregation mismatches strings, or migrated data shows scrambled hex. The MongoDB Java driver does not guess - you must configure UuidRepresentation and store values as BsonBinary subtype 04 (RFC) unless you explicitly integrate with legacy subtype 03 GUID bytes.
UUID representation setting
Use UuidRepresentation.STANDARD for greenfield apps (subtype 04 / RFC byte order). JAVA_LEGACY maps to subtype 03 Microsoft GUID layout - only when reading existing legacy data. Mixing representations across microservices causes “precision” symptoms that are really permuted bytes, not floating-point loss.
MongoClientSettings settings = MongoClientSettings.builder()
.uuidRepresentation(UuidRepresentation.STANDARD)
.applyConnectionString(new ConnectionString(uri))
.build();
BsonBinary, not ObjectId
UUIDs are 128-bit identifiers stored in BsonBinary with sixteen payload bytes. ObjectId is a different 12-byte type for MongoDB’s default _id - do not substitute one for the other. When tutorials mention “binary subtype,” they mean UUID subtype 04, not ObjectId.
Network byte order confusion is endianness within GUID vs RFC layouts - verify hex with the MongoDB UUID converter after changing representation.
Comparison issues in queries
Comparing java.util.UUID in filters only works when the stored BSON type matches. String literals in queries never equal Binary UUID fields. Custom comparators in application code that stringify differently from the driver codec create false negatives in unit tests - compare raw bytes in integration tests.
For cross-language contracts, assert canonical lowercase strings at the API boundary and BSON subtype 04 inside the database.
Spring Data MongoDB pitfalls
Ensure MongoCustomConversions does not register conflicting UUID converters. Propagate the same UuidRepresentation to every MongoTemplate bean in multi-tenant setups. Repository methods need UUID-typed parameters when the document field is Binary - not String.
Fix checklist for Java teams
- Set STANDARD representation on the client settings.
- Store _id as UUID type, not String, for new collections.
- Add golden tests: canonical string ↔ expected hex subtype 04.
- Migrate subtype 03 with byte permutation, not subtype byte alone.
- Log canonical UUID in dev; redact in production.
FAQ
- Should I use BsonObjectId for UUID?
- No. ObjectId is for 12-byte MongoDB IDs. UUIDs use 16-byte BsonBinary subtype 04.
- Why does getId return a different string than Compass?
- Usually endianness or String vs Binary storage. Align UuidRepresentation and field type.
- Does Lombok or mapping affect UUID bytes?
- Only if DTOs convert UUID to String with wrong format. Keep BSON type through the persistence layer.
Related: Java UUID conversion · Debug UUID encoding · Subtype 03 vs 04