How to store a UUID with binary subtype 0x04 using the MongoDB Java Driver

Viewed 341

I am trying to insert an Extended JSON document into a MongoDB collection. This document contains a standard UUID. My problem is that after inserting, the UUID is saved in the legacy LUUID format.

The following (Kotlin) program illustrates my problem:

import com.mongodb.MongoClientSettings
import com.mongodb.MongoCredential
import com.mongodb.ServerAddress
import com.mongodb.client.MongoClients
import com.mongodb.client.MongoCollection
import com.mongodb.connection.ClusterSettings
import org.bson.Document
import org.bson.UuidRepresentation
import org.bson.codecs.DocumentCodec
import org.bson.codecs.UuidCodec
import org.bson.codecs.configuration.CodecRegistries

fun connect(): MongoCollection<Document> =
    MongoClients.create(
        MongoClientSettings.builder()
            .credential(MongoCredential.createCredential("mongo", "admin", "mongo".toCharArray()))
            .applyToClusterSettings { builder: ClusterSettings.Builder ->
                builder.hosts(listOf(ServerAddress("localhost", 27017)))
            }
            .uuidRepresentation(UuidRepresentation.STANDARD)
            .build())
        .getDatabase("uuid-demo")
        .getCollection("collection")

fun parseDocument(json: String): Document =
    Document.parse(
        json,
        DocumentCodec(
            CodecRegistries.fromRegistries(
                CodecRegistries.fromCodecs(UuidCodec(UuidRepresentation.STANDARD)),
                MongoClientSettings.getDefaultCodecRegistry()
            )
        )
    )

fun main(args: Array<String>) {
    val document = parseDocument(
        """
        {
            "someId" : UUID("cfbca728-4e39-4613-96bc-f920b5c37e16")
        }        
        """.trimIndent()
    )
    val collection = connect()

    collection.drop()
    collection.insertOne(document)
    val inserted = collection.find().first()!!

    println(inserted.toJson())
}

However the UUID is stored using the LUUID type with binary subtype 0x03.

{"_id": {"$oid": "5fdb73cc7dab4766e448f2be"}, "someId": {"$binary": {"base64": "z7ynKE45RhOWvPkgtcN+Fg==", "subType": "03"}}}

What I am doing wrong here?

0 Answers
Related