How to Create UUID in MongoDB

Complete guide with examples and best practices

MongoDB supports UUIDs for document identifiers. Learn how to generate and use UUIDs in MongoDB Shell, Node.js, Python, and Mongoose with practical examples and ObjectId comparison.

Generate UUID for MongoDB

UUID()
550e8400-e29b-41d4-a716-446655440000

How to Generate UUID in MongoDB Shell

MongoDB provides a built-in UUID() function to create version 4 UUIDs directly in the MongoDB shell:

MongoDB Shell
// Generate a new UUID v4
UUID()  
// Returns: UUID("550e8400-e29b-41d4-a716-446655440000")

// Create document with UUID as _id
db.users.insertOne({
    _id: UUID(),
    name: "John Doe",
    email: "john@example.com",
    createdAt: new Date()
})

// Query by UUID
db.users.findOne({ 
    _id: UUID("550e8400-e29b-41d4-a716-446655440000") 
})

// Create multiple documents with auto-generated UUIDs
db.users.insertMany([
    { _id: UUID(), name: "Jane Smith", email: "jane@example.com" },
    { _id: UUID(), name: "Bob Johnson", email: "bob@example.com" }
])

Note: The UUID() function generates version 4 (random) UUIDs. MongoDB stores them as Binary subtype 4 for efficient storage and indexing.

UUID vs ObjectId: When to Use Each

MongoDB's default ObjectId and UUID serve different purposes. Choose based on your application needs:

Feature ObjectId UUID
Size 12 bytes 16 bytes
Sortable by Time ✓ Chronological Depends on version (v1, v7)
Cross-Database ✗ MongoDB specific ✓ Universal standard
Built-in Timestamp ✓ First 4 bytes v1 and v7 only
Best For MongoDB-only applications Multi-database systems, microservices

Recommendation: Use ObjectId for MongoDB-only apps for better performance. Use UUID when integrating with PostgreSQL, MySQL, or building microservices architecture.

How to Create UUID in Node.js with MongoDB Driver

The official MongoDB Node.js driver provides UUID support through the UUID class:

Node.js
const { MongoClient, UUID } = require('mongodb');
const { v4: uuidv4 } = require('uuid');

// Method 1: Using MongoDB's UUID helper
const user1 = {
    _id: new UUID(),  // Automatically generates UUID v4
    name: "John Doe",
    email: "john@example.com"
};

// Method 2: Using external uuid package
const user2 = {
    _id: new UUID(uuidv4()),  // Convert string UUID to Binary
    name: "Jane Smith",
    email: "jane@example.com"
};

// Insert into MongoDB
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('myapp');
const users = db.collection('users');

await users.insertOne(user1);
await users.insertOne(user2);

// Query by UUID
const foundUser = await users.findOne({ 
    _id: new UUID("550e8400-e29b-41d4-a716-446655440000") 
});

How to Use UUID with Mongoose

Mongoose requires custom configuration to use UUIDs as document identifiers:

Mongoose Schema
const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');

// Define schema with UUID as _id
const userSchema = new mongoose.Schema({
    _id: {
        type: String,
        default: () => uuidv4()
    },
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
}, { _id: false });  // Disable auto ObjectId generation

const User = mongoose.model('User', userSchema);

// Create new user (UUID auto-generated)
const newUser = new User({
    name: "John Doe",
    email: "john@example.com"
});

await newUser.save();

// Find by UUID
const user = await User.findById("550e8400-e29b-41d4-a716-446655440000");

How to Generate UUID in Python with PyMongo

Python's PyMongo driver supports UUIDs through the bson.binary module:

Python
from pymongo import MongoClient
from bson.binary import Binary, UuidRepresentation
import uuid

# Connect with UUID representation
client = MongoClient('mongodb://localhost:27017',
                     uuidRepresentation='standard')

db = client.myapp
users = db.users

# Generate UUID and insert
user_id = uuid.uuid4()
user_doc = {
    '_id': Binary.from_uuid(user_id),
    'name': 'John Doe',
    'email': 'john@example.com'
}

users.insert_one(user_doc)

# Query by UUID
user = users.find_one({'_id': Binary.from_uuid(user_id)})

# Convert Binary back to UUID
uuid_value = user['_id'].as_uuid()
print(uuid_value)  # 550e8400-e29b-41d4-a716-446655440000

Binary Storage and Performance

MongoDB stores UUIDs as Binary subtype 4 (UUID) for optimal storage and query performance:

Storage Comparison
// String storage (36 bytes) - NOT RECOMMENDED
{
    _id: "550e8400-e29b-41d4-a716-446655440000"
}

// Binary storage (16 bytes) - RECOMMENDED
{
    _id: UUID("550e8400-e29b-41d4-a716-446655440000")
}

// Check storage format
db.users.findOne()
// Shows: { _id: Binary(Buffer.from(...), 4) }

Performance Tip: Always use Binary UUID storage (16 bytes) instead of strings (36 bytes). This reduces index size by 55% and improves query performance.

Other Database UUID Guides

Copied!