Convert MongoDB binary UUID to string - cover art

MongoDB and UUID 14 min read

Convert MongoDB binary UUID to string: EJSON, shell, and drivers

July 7, 2026 · 14 min read

Binary UUIDs are efficient in the database but awkward in spreadsheets, email tickets, and curl debugging. Every production team eventually needs a reliable path from BSON Binary → canonical string that preserves subtype semantics and RFC byte order. The good news: MongoDB ships multiple conversion surfaces - Extended JSON, mongosh helpers, driver methods, and aggregation operators - so you rarely need custom bit math unless you are repairing legacy subtype 03 data.

Reading UUIDs from Extended JSON

When you export a document with mongoexport --jsonFormat=canonical or Atlas Data Explorer, UUID fields appear as $binary objects with base64 payload and subType. Decoding base64 yields 16 bytes; applying the correct endianness interpretation yields the canonical hyphenated string. Tools that ignore subType and decode as generic binary often display misleading hex.

For automation, parse Extended JSON with the same library that produced it - BSON parsers in drivers understand subtype 04 natively and return a UUID object whose toString() is canonical. Piping through jq without BSON awareness forces you to reimplement subtype rules.

Converting in mongosh interactively

mongosh can construct UUID values from strings and print them readably when querying. If you fetch a document and see Binary subtype 4, use UUID helpers rather than calling toString() on raw Binary, which may default to base64. The shell’s UUID() constructor is also the quickest way to test queries against sample IDs copied from application logs.

// mongosh
const doc = db.orders.findOne({ status: "open" });
const id = doc._id; // UUID object if stored as subtype 4
print(id.toString()); // canonical string

// From Extended JSON literal in a script:
const fromEjson = UUID("550e8400-e29b-41d4-a716-446655440000");
print(fromEjson);

For ad hoc aggregation, project string forms only in the final stage sent to humans; keep binary inside the pipeline so indexes remain usable on earlier $match stages.

Node.js and Python driver patterns

In Node’s mongodb package, values returned as UUID class instances stringify to canonical form with toString() or toHexString() depending on version - consult your driver minor version docs because APIs evolved. In PyMongo, uuid.UUID objects round-trip automatically when BSON subtype is configured to the standard UUID representation.

When serializing API responses, convert once at the controller boundary rather than letting JSON serializers guess. Explicit conversion functions make OpenAPI schemas truthful and prevent accidental base64 in public JSON.

Aggregation and server-side string projection

Server versions that expose $toString on UUID types can project canonical strings inside the database. This helps reporting views but can prevent index use if you wrap indexed fields unnecessarily. Prefer matching on binary UUID parameters from the application and projecting strings only for display fields.

For large exports, streaming cursors with per-document conversion in application code often beats heavy aggregation pipelines that materialize wide string columns in memory.

Exports, logs, and observability

Structured logs should carry both a string UUID for humans and, optionally, a base64 binary form for machines - pick one canonical column in your log schema to avoid double-storage. When shipping traces to OpenTelemetry, stringify at the SDK using the same function your MongoDB writers use so trace IDs correlate with document keys.

CSV exports from BI connectors frequently flatten binary to unreadable blobs. Pre-convert in a SQL view or MongoDB view with a defined string field name so analysts do not hand-edit hex in Excel.

If you maintain GraphQL or gRPC APIs in front of MongoDB, define scalar types that always emit canonical strings to clients while keeping binary in the persistence layer. Document that wire format in your schema so mobile clients never persist returned strings back as binary without parsing through the same codec your server uses.

For one-off DBA tasks, piping a single document through bsondump and a small Node script is faster than teaching everyone hex by hand - but production pipelines should still centralize conversion in a shared library with unit tests rather than ad hoc scripts checked into personal dotfiles.

Watch timezone and locale settings in log aggregation: they do not change UUID bytes, but they change how timestamps adjacent to UUIDs are rendered, which can mislead investigators into thinking the identifier itself mutated when only the surrounding metadata was formatted differently.

Treat conversion utilities as part of your platform SDK: version them, sign them, and publish changelog notes when subtype handling changes so application teams do not fork divergent copy-paste helpers from Stack Overflow answers.

FAQ

Why does mongoexport show base64 instead of hyphens?
Canonical Extended JSON represents BSON Binary literally. Decode with subtype-aware tools to obtain hyphenated strings.
Is hex or string better in application logs?
Canonical lowercase strings are easiest for grep and support tickets. Include subtype context if logs capture raw binary.
Can aggregation convert without the application?
Yes on recent servers with UUID-aware operators, but watch performance on large collections. Application-side conversion is often clearer to test.
Do I need different code for subtype 03?
Yes. Use a GUID-aware conversion when subType is 03; treating bytes as RFC 04 will produce the wrong string if endianness differs.

Related: Internal UUID storage · Subtype 03 vs 04 · MongoDB UUID converter · Java conversion guide

Browse all tools