MongoDB, or Mongo compatible DocumentDB, saves their data in Binary JSON (BSON). They used to save their UUIDs as binary subtype 0x03, but the interpretation was not similar in a multi-platform environment and caused issues. Therefore, the 0x04 was introduced.

However, when saving UUIDs in your MongoDB using the MongoDB Java driver, it will result in a 0x03 subtype by default. You need to specify if you would like to save UUIDs as 0x04 subtype. This is done with implementations of the Codec interface. A lot of CodecProvider s are already shipped with the Mongo driver. Such as the UuidCodecProvider. You probably think 'if I add this provider, my UUIDs will be correctly saved in the database and I can query it subsequently'. Well…​ No.

By default the UuidCodecProvider uses the legacy representation of UUID used by the Java driver (Legacy UUID, a.k.a. LUUID). If your Java UUIDs are saved as LUUIDs in Mongo, it gets complicated to query them by UUID. You can fix this by saving the UUIDs as actual UUIDs (subtype 0x04). Simply add the correct UUID representation in the constructor of the provider:

new UuidCodecProvider(UuidRepresentation.STANDARD) // save as UUID

instead of

new UuidCodecProvider() // save as LUUID

or

new UuidCodecProvider(UuidRepresentation.JAVA_LEGACY) // save as LUUID

Now, you can use the UUID to query!

db.yourCollection.where("someId").eq(UUID("1e54dd51-6d00-4a52-b727-05ccca8b442d"))

MongoDB configuration with Spring Boot:

package com.jcore.mongo;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.UuidRepresentation;
import org.bson.codecs.UuidCodecProvider;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DocumentDbConfiguration {

    @Bean
    public MongoDatabase mongoDatabase(String clusterUrl, String databaseName) {
        return MongoClients
            .create(buildMongoClientSettings(clusterUrl))
            .getDatabase(databaseName)
            .withCodecRegistry(codecRegistries());
    }

    private MongoClientSettings buildMongoClientSettings(String clusterUrl) {
        return MongoClientSettings.builder()
            .applyConnectionString(new ConnectionString(clusterUrl))
            .build();
    }

    private CodecRegistry codecRegistries() {
        return CodecRegistries.fromRegistries(
            // save uuids as UUID, instead of LUUID
            CodecRegistries.fromProviders(new UuidCodecProvider(UuidRepresentation.STANDARD)),
            MongoClientSettings.getDefaultCodecRegistry()
        );
    }
}
shadow-left