MongoDB
UUID
BinData
Data Conversion
Programming

Get a BinData UUID from MongoDB as a string

Codemia Knowledge Hub ·

MongoDB stores UUIDs as BinData, usually subtype 4. To get one back as a string, convert the binary value to hex and format it into the usual dashed UUID layout, either in the Mongo shell or in your driver code (for example with uuid.stringify in Node.js).

BinData and UUIDs in MongoDB

BinData is a BSON type for binary data, such as JSON web tokens, encrypted information, or data encoded in formats like UUIDs. It supports several subtypes, including general binary data, functions and UUIDs.

A UUID (Universally Unique Identifier) is a 128-bit label used across systems to identify information uniquely. MongoDB can store it as a BinData subtype, which is more efficient for performance and storage than a string representation. Systems that expect strings, though, need it converted.

A UUID stored as BinData looks like this:

 
{ "_id" : ObjectId("..."), "uuidField" : BinData(4, "UVERSDEzLTQ1NzY...") }

The BinData type "4" marks a standard UUID.

Converting in the Mongo shell

In the MongoDB shell you can convert with JavaScript:

javascript
1// Let's assume 'myCollection' is the collection containing UUIDs
2db.myCollection.find().forEach(function(doc) {
3    var uuidBuffer = doc.uuidField;
4    var uuidHex = uuidBuffer.toString('hex');
5    var uuidAsString = [
6      uuidHex.substring(0, 8),
7      uuidHex.substring(8, 12),
8      uuidHex.substring(12, 16),
9      uuidHex.substring(16, 20),
10      uuidHex.substring(20)
11    ].join('-');
12    
13    print("UUID as String: " + uuidAsString);
14});

Converting with the Node.js driver

With a driver the approach is the same, with slightly different syntax:

javascript
1const { MongoClient } = require('mongodb');
2const uuid = require('uuid');
3
4// Connect to MongoDB
5const client = new MongoClient("mongodb://localhost:27017");
6client.connect().then(() => {
7    const db = client.db("myDatabase");
8    const collection = db.collection("myCollection");
9
10    return collection.find().forEach(doc => {
11        let binDataUUID = doc.uuidField.buffer;
12        let stringUUID = uuid.stringify(binDataUUID);
13        console.log("UUID as String:", stringUUID);
14    });
15}).catch(err => console.error(err)).finally(() => client.close());

Trade-offs of storing BinData and converting

  • Storage and processing: BinData is storage-efficient, but converting to strings costs processing time. Do the conversion where its performance impact is smallest.
  • Compatibility: UUIDs are common in system integrations, and a string form is needed for platforms that don't understand Mongo's binary UUID format.
  • Security: treat converted values with the same care as any sensitive data, and transport them over secure, encrypted connections.
FeatureBinData StorageString Representation
EfficiencyHigh storage efficiencySlower upon conversion
UUID FormatBinData subtype "4" (UUID)Alphanumeric with dashes
Usage CompatibilityDirect in MongoDBRequired for external applications
PerformanceFaster native operationsConversion can be resource-intensive
Storage ConcernsMinimal space usageRequires extra computation for conversion
Security PracticesKeep data secure at restEnsure secure transmission and usage

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design