Skip to content

Instantly share code, notes, and snippets.

@gavvvr
Last active December 16, 2022 06:14
Show Gist options
  • Save gavvvr/4e01f2d26b42c71e50892be0fee9de8e to your computer and use it in GitHub Desktop.
Save gavvvr/4e01f2d26b42c71e50892be0fee9de8e to your computer and use it in GitHub Desktop.
Migrate UUID values from legacy binary type 3 to standard

MongoDB migration: From legacy UUID represenation (binary type 3) to standard (type 4)

You may face the need to migrate your data, because legacy format was a default choice for a long time in Spring Boot/Data MongoDB and the official MongoDB driver itself (more details here).

So, here is the Java solution based on utilitites from Mongo's org.bson:bson to perform the migration.

import org.bson.BsonBinary;
import org.bson.Document;
import org.bson.internal.UuidHelper;
import org.bson.types.Binary;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import static org.bson.BsonBinarySubType.UUID_LEGACY;
import static org.bson.BsonBinarySubType.UUID_STANDARD;
import static org.bson.UuidRepresentation.JAVA_LEGACY;
import static org.bson.UuidRepresentation.STANDARD;
public class MongoDBUuidRepresentationMigrator {
public static boolean convertUuidValuesFromLegacyToStandardFor(Document rootDocument) {
boolean docWasChanged = false;
Queue<Document> queue = new LinkedList<>();
queue.offer(rootDocument);
while (!queue.isEmpty()) {
Document document = queue.remove();
for (Map.Entry<String, Object> kv : document.entrySet()) {
String fieldName = kv.getKey();
Object fieldValue = kv.getValue();
if (fieldValue instanceof Binary && ((Binary) fieldValue).getType() == UUID_LEGACY.getValue()) {
migrateUuidRepresentationFromLegacyToStandard(document, fieldName);
docWasChanged = true;
} else if (fieldValue instanceof Document) {
queue.add(document);
}
}
}
return docWasChanged;
}
private static void migrateUuidRepresentationFromLegacyToStandard(Document document, String key) {
Binary legacyBinary = (Binary) document.get(key);
UUID uuid = new BsonBinary(legacyBinary.getType(), legacyBinary.getData()).asUuid(JAVA_LEGACY);
document.put(key, new BsonBinary(UUID_STANDARD, UuidHelper.encodeUuidToBinary(uuid, STANDARD)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment