Guides

ObjectId to UUID Conversion Guide

How to convert MongoDB ObjectIds to UUIDs when migrating to SQL databases. Covers conversion strategies, handling references, and preserving sortability.

Why Convert ObjectId to UUID?

MongoDB's ObjectId is a 12-byte BSON type — it's not a standard SQL type. Most SQL databases don't have an equivalent. UUID (Universally Unique Identifier) is a 16-byte standardized identifier supported natively by PostgreSQL, MySQL, SQL Server, and others. Converting ObjectId to UUID makes your data portable and queryable using standard SQL tools.

ObjectId Structure

A MongoDB ObjectId consists of: 4 bytes — Unix timestamp (seconds since epoch), 5 bytes — random value (unique per process), and 3 bytes — incrementing counter. This structure makes ObjectIds roughly sortable by creation time, which is useful for chronological queries without an explicit createdAt field.

Conversion Strategy: Deterministic Mapping

NoSQLSync uses a deterministic mapping: the 12-byte ObjectId is zero-padded to 16 bytes to form a UUID. This preserves the original value and makes the conversion reversible — given the UUID, you can extract the original ObjectId. All ObjectId references in other collections are automatically remapped to the corresponding UUIDs.

Preserving Sort Order

Because ObjectIds embed a timestamp, they sort approximately by creation time. When converting to UUID, this sort order is lost — standard UUIDs (v4) are random. NoSQLSync preserves an optional `__original_objectid` column or extracts the timestamp into a `created_at` column so you can still sort chronologically.

Handling ObjectId References

If your MongoDB collections use ObjectIds as references (similar to foreign keys), NoSQLSync detects these during schema inference. It builds a reference map: when document A references document B by ObjectId, the reference is updated to use the new UUID of document B. This keeps relationships intact after migration.

Related resources
MongoDB to PostgreSQL migrationWhat is schema mapping?

Start your migration today

Put these concepts into practice. Free plan includes 3 migrations per month.

Start free →