MongoDB’s flexible document model supports UUID primary keys via the BSON Binary type with subtype 4 (UUID). UUID v7 is a strong choice for MongoDB document IDs: its timestamp prefix makes documents sort chronologically by _id, and it integrates cleanly with SQL databases using the same UUID format. See UUID in MongoDB for the migration-from-ObjectId context.
Node.js driver — UUID v7 as _id
import { MongoClient, Binary, UUID } from 'mongodb';
import { v7 as uuidv7, parse as uuidParse } from 'uuid';
const client = new MongoClient(process.env.MONGO_URI!);
const db = client.db('app');
const orders = db.collection('orders');
async function createOrder(customerId: string, status: string) {
const rawId = uuidParse(uuidv7()); // 16-byte Uint8Array
const bsonId = new Binary(Buffer.from(rawId), Binary.SUBTYPE_UUID);
const result = await orders.insertOne({
_id: bsonId,
customerId,
status,
createdAt: new Date(),
});
return uuidv7(); // return as string for the API response
}
Binary.SUBTYPE_UUID (subtype 4) stores the 16 raw bytes — the most compact MongoDB UUID representation. The uuid npm package’s parse() converts the hyphenated string to a Uint8Array. See UUID in JavaScript for the full Node.js context.
UUID v7 helper collection wrapper
// lib/mongo-uuid.ts
import { Collection, Binary, Filter } from 'mongodb';
import { v7 as uuidv7, parse as uuidParse } from 'uuid';
export function toUuidBinary(uuid: string): Binary {
return new Binary(Buffer.from(uuidParse(uuid)), Binary.SUBTYPE_UUID);
}
export function newDocId(): Binary {
return toUuidBinary(uuidv7());
}
// Time-range lower bound: all UUID v7 docs created after a given timestamp
export function uuidV7LowerBound(ms: number): Binary {
const hex = ms.toString(16).padStart(12, '0');
const uuid = `${hex.slice(0,8)}-${hex.slice(8,12)}-7000-8000-000000000000`;
return toUuidBinary(uuid);
}
// Query orders created in the last hour
const since = uuidV7LowerBound(Date.now() - 3_600_000);
const recent = await orders
.find({ _id: { $gte: since } })
.sort({ _id: 1 })
.toArray();
BSON Binary values compare by byte order — UUID v7’s timestamp prefix makes $gte / $lte range queries on _id chronological. See Time Precision for the 48-bit millisecond detail.
Python driver — PyMongo
from pymongo import MongoClient
from bson.binary import Binary, UUID_SUBTYPE
import uuid
client = MongoClient(os.environ['MONGO_URI'])
db = client['app']
orders = db['orders']
def create_order(customer_id: str, status: str) -> str:
order_id = uuid.uuid7() # Python 3.13+
binary_id = Binary(order_id.bytes, UUID_SUBTYPE)
orders.insert_one({
'_id': binary_id,
'customer_id': customer_id,
'status': status,
})
return str(order_id)
order_id.bytes converts the Python UUID object to its 16-byte big-endian representation — matching the BSON Binary UUID byte order. See UUID in Python and Python 3.13 uuid.uuid7().
String storage alternative
For simpler debugging, store UUID v7 as a plain string:
await orders.insertOne({
_id: uuidv7(), // stored as string — 36 bytes vs 16 for Binary
status: 'pending',
});
// String comparison still works for range queries
const recent = await orders
.find({ _id: { $gte: '018fbe3a-0000-7000-8000-000000000000' } })
.sort({ _id: 1 })
.toArray();
String storage is fine for moderate-scale collections. Binary is recommended for collections over ~10M documents where the 20-byte overhead per document becomes material.
Further reading
- UUID in MongoDB — replacing ObjectId
- UUID in JavaScript — full guide
- UUID in Python — full guide
- UUID in Databases — storage and indexing
- UUID v7 for Cursor Pagination
- Shard Key — UUID v7 for distributed databases
External references
Frequently asked questions
Should I use MongoDB ObjectId or UUID v7 as document IDs?
ObjectId is 12 bytes (vs UUID's 16) and already time-sortable — it embeds a 4-byte Unix timestamp. UUID v7 is preferable when: IDs must be globally unique across collections or external systems, the system also uses PostgreSQL or another UUID-native database (same ID format everywhere), or IDs are exposed in APIs where ObjectId's binary string representation is inconvenient. See UUID in MongoDB — Replacing ObjectId with UUID v7.
How does MongoDB store UUID v7 values?
The Node.js driver's new Binary(buffer, Binary.SUBTYPE_UUID) stores UUIDs as BSON Binary subtype 4 — 16 bytes, the most compact representation. Alternatively, store as a plain string (string field) — easier to read in logs but uses 36 bytes. For production, prefer Binary subtype 4 for storage efficiency. See UUID in Databases — storage and indexing.