Skip to content

Generate UUID in MongoDB

MongoDB provides several ways to generate unique identifiers. The default ObjectId is MongoDB's native 12-byte identifier, while standard UUIDs can be generated using the UUID() function:

javascript
// MongoDB's default ObjectId (12 bytes, time-ordered)
ObjectId()
// Result: ObjectId("507f1f77bcf86cd799439011")

// Generate UUID version 4 (16 bytes, random)
UUID()
// Result: UUID("550e8400-e29b-41d4-a716-446655440000")

// Convert UUID to BinData for storage
BinData(3, "VQ6EAOKbQdSnFkRmVUQAAA==")

MongoDB supports different UUID generation methods depending on your needs:

javascript
// ObjectId - MongoDB's default (time-ordered, 12 bytes)
db.users.insertOne({
    _id: ObjectId(),
    name: "John Doe",
    email: "[email protected]"
});

// UUID v4 - Standard random UUID (16 bytes)
db.users.insertOne({
    _id: UUID(),
    name: "Jane Doe", 
    email: "[email protected]"
});

// Custom UUID field (keeping ObjectId as _id)
db.users.insertOne({
    _id: ObjectId(),
    uuid: UUID(),
    name: "Bob Smith",
    email: "[email protected]"
});

// UUID stored as BinData for efficiency
db.users.insertOne({
    _id: ObjectId(),
    uuid: BinData(3, "VQ6EAOKbQdSnFkRmVUQAAA=="),
    name: "Alice Johnson",
    email: "[email protected]"
});

Collection Schema with UUID Fields

Using ObjectId (MongoDB default):

javascript
// Create collection with ObjectId
db.createCollection("users");

// Insert documents (ObjectId generated automatically)
db.users.insertMany([
    {
        name: "John Doe",
        email: "[email protected]",
        createdAt: new Date()
    },
    {
        name: "Jane Smith", 
        email: "[email protected]",
        createdAt: new Date()
    }
]);

// Query by ObjectId
db.users.findOne({_id: ObjectId("507f1f77bcf86cd799439011")});

// Create index on ObjectId (automatic)
db.users.createIndex({_id: 1});

Using UUID fields:

javascript
// Create collection with UUID fields
db.orders.insertOne({
    _id: ObjectId(),
    orderId: UUID(),
    userId: UUID("550e8400-e29b-41d4-a716-446655440000"),
    items: [
        {
            itemId: UUID(),
            name: "Product A",
            quantity: 2
        }
    ],
    total: 99.99,
    createdAt: new Date()
});

// Create indexes on UUID fields
db.orders.createIndex({orderId: 1}, {unique: true});
db.orders.createIndex({userId: 1});

// Query by UUID
db.orders.find({userId: UUID("550e8400-e29b-41d4-a716-446655440000")});

Advanced MongoDB UUID Usage

UUID utility functions:

javascript
// Function to generate UUID v4
function generateUUIDv4() {
    return UUID();
}

// Function to validate UUID format
function isValidUUID(uuid) {
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    return uuidRegex.test(uuid.toString());
}

// Function to convert string to UUID
function stringToUUID(uuidString) {
    return UUID(uuidString);
}

// Usage examples
const newUUID = generateUUIDv4();
const isValid = isValidUUID(newUUID);
const convertedUUID = stringToUUID("550e8400-e29b-41d4-a716-446655440000");

Aggregation with UUIDs:

javascript
// Aggregation pipeline with UUID matching
db.orders.aggregate([
    {
        $match: {
            userId: UUID("550e8400-e29b-41d4-a716-446655440000")
        }
    },
    {
        $group: {
            _id: "$userId",
            totalOrders: {$sum: 1},
            totalAmount: {$sum: "$total"}
        }
    }
]);

// Lookup with UUID fields
db.orders.aggregate([
    {
        $lookup: {
            from: "users",
            localField: "userId",
            foreignField: "uuid",
            as: "userDetails"
        }
    },
    {
        $unwind: "$userDetails"
    }
]);

Performance Optimization

UUID indexing strategies:

javascript
// Compound indexes with UUID
db.events.createIndex({
    userId: 1,
    eventType: 1,
    createdAt: -1
});

// Sparse index for optional UUID fields
db.sessions.createIndex(
    {sessionId: 1}, 
    {unique: true, sparse: true}
);

// Partial index with UUID condition
db.users.createIndex(
    {uuid: 1},
    {
        partialFilterExpression: {
            uuid: {$exists: true}
        }
    }
);

UUID storage optimization:

javascript
// Store UUID as BinData for better performance
db.users.insertOne({
    _id: ObjectId(),
    uuid: BinData(3, "VQ6EAOKbQdSnFkRmVUQAAA=="), // More efficient
    name: "John Doe"
});

// vs storing as string (less efficient)
db.users.insertOne({
    _id: ObjectId(),
    uuid: "550e8400-e29b-41d4-a716-446655440000", // Less efficient
    name: "Jane Doe"
});

// Query BinData UUID
db.users.find({
    uuid: BinData(3, "VQ6EAOKbQdSnFkRmVUQAAA==")
});

Node.js Driver Integration

Using MongoDB Node.js driver:

javascript
const { MongoClient, ObjectId } = require('mongodb');
const { v4: uuidv4 } = require('uuid');

async function examples() {
    const client = new MongoClient('mongodb://localhost:27017');
    const db = client.db('testdb');
    const collection = db.collection('users');

    // Insert with ObjectId
    await collection.insertOne({
        _id: new ObjectId(),
        name: 'John Doe',
        email: '[email protected]'
    });

    // Insert with UUID (as string)
    await collection.insertOne({
        _id: new ObjectId(),
        uuid: uuidv4(),
        name: 'Jane Doe',
        email: '[email protected]'
    });

    // Insert with UUID as Binary
    const uuid = uuidv4();
    const binaryUUID = Buffer.from(uuid.replace(/-/g, ''), 'hex');
    
    await collection.insertOne({
        _id: new ObjectId(),
        uuid: binaryUUID,
        name: 'Bob Smith',
        email: '[email protected]'
    });

    // Query by UUID
    const user = await collection.findOne({
        uuid: uuidv4('550e8400-e29b-41d4-a716-446655440000')
    });
}

Mongoose integration:

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

// Schema with UUID field
const userSchema = new mongoose.Schema({
    uuid: {
        type: String,
        default: uuidv4,
        unique: true
    },
    name: String,
    email: String,
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// Schema with Binary UUID for better performance
const optimizedUserSchema = new mongoose.Schema({
    uuid: {
        type: Buffer,
        default: () => Buffer.from(uuidv4().replace(/-/g, ''), 'hex')
    },
    name: String,
    email: String
});

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

Sharding and Replication

UUID considerations for sharding:

javascript
// Good shard key: UUID provides good distribution
sh.shardCollection("mydb.users", {uuid: 1});

// Compound shard key with UUID
sh.shardCollection("mydb.events", {userId: 1, eventId: 1});

// Query with shard key
db.users.find({uuid: UUID("550e8400-e29b-41d4-a716-446655440000")});

Replica set considerations:

javascript
// UUIDs work perfectly with replica sets
// No special configuration needed

// Write concern with UUID operations
db.users.insertOne(
    {
        uuid: UUID(),
        name: "John Doe"
    },
    {
        writeConcern: {
            w: "majority",
            j: true
        }
    }
);

Migration and Data Import

Converting ObjectId to UUID:

javascript
// Add UUID field to existing documents
db.users.updateMany(
    {uuid: {$exists: false}},
    [{
        $set: {
            uuid: {$function: {
                body: "function() { return UUID(); }",
                args: [],
                lang: "js"
            }}
        }
    }]
);

// Bulk update with UUIDs
db.users.bulkWrite([
    {
        updateMany: {
            filter: {uuid: null},
            update: {$set: {uuid: UUID()}}
        }
    }
]);

Data import with UUIDs:

javascript
// Import CSV with UUID generation
const users = [
    {name: "John", email: "[email protected]"},
    {name: "Jane", email: "[email protected]"}
];

const documentsWithUUID = users.map(user => ({
    ...user,
    uuid: UUID(),
    createdAt: new Date()
}));

db.users.insertMany(documentsWithUUID);

UUID Version Comparison

Choose the right identifier for your MongoDB application:

  • ObjectId - MongoDB's default, 12 bytes, time-ordered, includes machine/process info
  • Version 1 - Time-based UUID, 16 bytes, includes MAC address
  • Version 4 - Random UUID, 16 bytes, maximum entropy
  • Version 5 - SHA-1 namespace-based, deterministic
  • Version 7 - Modern time-based, better than v1

For MongoDB applications:

  • Native MongoDB apps: Use ObjectId for optimal performance
  • Cross-system compatibility: Use Version 4 UUIDs
  • Time-series data: Consider Version 7 for better ordering
  • Distributed systems: Use Version 5 for deterministic IDs

How do I generate UUID in other databases?

SQL databases:

  • PostgreSQL - Comprehensive UUID support with extensions
  • MySQL - Built-in UUID() function
  • SQL Server - NEWID() and NEWSEQUENTIALID()
  • SQLite - Custom functions and extensions

NoSQL databases:

  • Redis - UUID generation with Lua scripts
  • Cassandra - Built-in UUID functions
  • DynamoDB - UUID generation in application code

← Back to Online UUID Generator