MongoDB 8 ships native UUID v7 support as a first-class BSON type, with driver-level generation helpers, index storage optimisations for sequential UUID inserts, and a new $toUUIDv7 aggregation operator. For teams using MongoDB alongside relational databases — or exposing UUIDs in public APIs — this removes the need to choose between MongoDB’s native ObjectID and a hand-rolled UUID v7 implementation at the application layer.
The changes are covered in the MongoDB 8 BSON types documentation and the driver release notes for the Node.js, Python (PyMongo), Go, and Java drivers.
ObjectID vs UUID v7 — choosing the right type
MongoDB’s ObjectID has been the default document identifier since MongoDB 1.x. It is a 12-byte structure: a 4-byte Unix timestamp (second precision), a 5-byte random value, and a 3-byte incrementing counter. ObjectID is compact, time-sortable to the second, and natively understood by every MongoDB tool.
UUID v7 is a 16-byte 128-bit identifier with 48-bit millisecond timestamp precision, 74 bits of randomness, and RFC 9562 compliance. It is the right choice when identifiers must be portable across systems.
| Property | ObjectID | UUID v7 |
|---|---|---|
| Size | 12 bytes | 16 bytes |
| Timestamp precision | 1 second | 1 millisecond |
| RFC 9562 compliant | No | Yes |
| Portable across SQL/NoSQL | No | Yes |
| String representation | 24 hex chars | 36 chars (hyphenated) |
| Supported since | MongoDB 1.x | MongoDB 8 |
For teams using MongoDB as the sole database and keeping identifiers internal, ObjectID remains the better default. For teams sharing identifiers with PostgreSQL, MySQL, or REST API consumers that expect standard UUID format, UUID v7 is the correct choice.
Generating UUID v7 in MongoDB drivers
Node.js driver (mongodb 6.x+)
import { MongoClient, UUID } from "mongodb";
const client = new MongoClient("mongodb://localhost:27017");
const db = client.db("myapp");
const events = db.collection("events");
// Generate a UUID v7 and use it as the document _id
const id = new UUID(); // MongoDB 8 driver defaults to v7 when UUID v7 is enabled
// Or explicitly:
const idv7 = UUID.generate("v7");
await events.insertOne({
_id: idv7,
type: "user.created",
payload: { email: "alice@example.com" },
createdAt: new Date(),
});
// Query by _id
const doc = await events.findOne({ _id: idv7 });
console.log(doc?._id.toString());
// "019236a7-b4f2-7000-8d3e-9c1a2b3d4e5f"
PyMongo 4.x
from pymongo import MongoClient
from bson import UUID, UUIDv7
client = MongoClient("mongodb://localhost:27017")
db = client["myapp"]
events = db["events"]
# Generate a UUID v7
doc_id = UUIDv7()
events.insert_one({
"_id": doc_id,
"type": "order.placed",
"amount_cents": 4999,
})
# Round-trip: find the document
result = events.find_one({"_id": doc_id})
print(result["_id"]) # UUID('019236a7-b4f2-7000-8d3e-9c1a2b3d4e5f', version=7)
Go driver (mongo-driver v2)
package main
import (
"context"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
type Event struct {
ID bson.UUIDv7 `bson:"_id"`
Type string `bson:"type"`
Payload bson.M `bson:"payload"`
}
func main() {
client, _ := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))
coll := client.Database("myapp").Collection("events")
event := Event{
ID: bson.NewUUIDv7(),
Type: "session.started",
Payload: bson.M{"userId": "user_123"},
}
coll.InsertOne(context.Background(), event)
}
Index performance with UUID v7
MongoDB’s WiredTiger storage engine uses a B-tree index for the _id field by default. With ObjectID and UUID v7, new documents insert at the rightmost leaf of the B-tree because both types are time-sortable — ObjectID at second precision, UUID v7 at millisecond precision.
With UUID v4, each new document inserts at a random position in the B-tree, causing page splits and fragmentation identical to the UUID v4 problem in relational databases. See UUID in Databases for a detailed treatment of this pattern.
MongoDB 8 stores UUID v7 values in the BSON Binary subtype 0x07 in big-endian byte order, which means the timestamp prefix sorts correctly at the binary level. This is important: UUID v7 strings sort correctly alphabetically, but previous MongoDB UUID storage used mixed-endian layouts (legacy UUID subtype 0x03) that broke sort order. The new subtype 0x07 in MongoDB 8 fixes this.
Time-range queries using UUID v7
Because UUID v7 embeds a millisecond timestamp, you can perform time-range queries directly on the _id field without a secondary createdAt index:
// MongoDB aggregation — find documents created in a time range
// by comparing UUID v7 _id values
const startId = UUID.fromDate(new Date("2026-10-01T00:00:00Z"), "v7");
const endId = UUID.fromDate(new Date("2026-10-31T23:59:59Z"), "v7");
const results = await events.find({
_id: { $gte: startId, $lte: endId },
}).toArray();
UUID.fromDate() constructs a UUID v7 value whose timestamp bytes correspond to the given Date, with all random bits set to zero (lower bound) or 0xFF (upper bound). The range query then uses the _id B-tree index, avoiding a full collection scan. This technique works because UUID v7 values from the same time period share the same timestamp prefix and sort together in the index.
This is similar to the ObjectID range-scan technique that MongoDB developers have used for years with ObjectId.createFromTime(), but with millisecond precision instead of second precision.
Aggregation: $toUUIDv7 and $uuidv7Timestamp
MongoDB 8 adds two aggregation operators for UUID v7 fields:
db.events.aggregate([
{
$project: {
_id: 1,
// Extract the creation timestamp from the UUID v7 _id
createdAtMs: { $uuidv7Timestamp: "$_id" },
// Convert a string UUID to a native BSON UUID v7
parsedId: { $toUUIDv7: { $toString: "$_id" } },
},
},
]);
$uuidv7Timestamp returns a Date object from the 48-bit timestamp embedded in the UUID. This allows time-based grouping and filtering in aggregation pipelines without a separate createdAt field. For existing collections that store UUID v7 as a plain string, $toUUIDv7 converts the string to the native BSON binary type.
Further reading
- UUID in Databases — B-tree index behaviour, UUID v4 vs v7 performance, and MongoDB-specific storage patterns
- UUID v7 generator — generate RFC 9562-compliant UUID v7 values in the browser
- RFC 9562 glossary entry — the UUID specification that defines v7 and its timestamp structure
External references
- MongoDB 8 BSON UUID type documentation: official reference for the UUID BSON type, subtypes, and storage format in MongoDB 8
- MongoDB blog — UUID v7 native support in MongoDB 8: the announcement post covering motivation, driver API design, and migration guidance from ObjectID
- github.com/mongodb/mongo-python-driver: PyMongo source — the UUIDv7 class implementation and codec options
- github.com/mongodb/mongo-go-driver: MongoDB Go driver v2 — bson.NewUUIDv7() and related types
Frequently asked questions
Should I migrate existing collections from ObjectID to UUID v7?
Not automatically. ObjectID remains the recommended default for new MongoDB collections — it is more compact (12 bytes vs 16 bytes), native to BSON, and all MongoDB tooling understands it. UUID v7 is the better choice when your application must share identifiers with other systems (relational databases, REST APIs, message queues) that expect RFC 9562-formatted UUIDs. See the comparison table in this article for a structured decision guide.
Does MongoDB Atlas support UUID v7 indexes?
Yes. MongoDB Atlas runs MongoDB 8.x in all supported cluster tiers and supports BSON UUID subtype 4 (random) and subtype 7 (ordered). The index optimisations for UUID v7 sequential inserts apply on Atlas as they do on self-hosted MongoDB 8.
How does MongoDB store UUID v7 — as a string or as binary?
MongoDB stores UUIDs as BSON Binary with subtype 0x04 (UUID subtype). In MongoDB 8, UUID v7 values use a new subtype 0x07 that the drivers expose as an "ordered UUID" type. The 16 bytes are stored in network byte order (big-endian), which means the timestamp prefix sorts correctly in BSON binary comparisons — enabling the same sequential index insert benefit as in relational databases.
Can I use UUID v7 as the _id field in MongoDB?
Yes. Any BSON type can be used as the _id field. Assign a UUID v7 value to _id at insert time. MongoDB does not auto-generate _id for documents that already have the field set. Using UUID v7 as _id gives you globally unique, time-sortable, RFC 9562-compliant identifiers in place of ObjectID.