Skip to main content

How to Create UUID in MongoDB

Complete guide with examples and best practices

In the mongosh shell, MongoDB's built-in UUID() helper generates a version 4 identifier as a native BSON Binary value, so you get a MongoDB UUID without installing a single driver or library. It still displays with the familiar hyphenated formatting, but MongoDB stores it as 16 raw bytes internally rather than a 36-character string. Below you'll find copy-paste ready mongosh commands for generating a UUID, converting an existing UUID string into the BSON type, and the driver-level options for generating UUIDs from application code. The postgres uuid generator reference covers UUID primary keys, BRIN indexes, and partitioning strategies in PostgreSQL.

Generate UUID for MongoDB

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

How to Generate a UUID in MongoDB

The simplest way to generate a UUID in MongoDB is the built-in UUID() helper, available directly in the mongosh shell — no driver, package, or extension required. Use the uuid v5 generator when you need the same UUID every time for the same input — deterministic generation.

mongosh
const id = UUID();
print(id);
// Output: UUID("550e8400-e29b-41d4-a716-446655440000")

Explanation

Convert a String to a UUID in MongoDB

A UUID sent as a string — from an API request or an application layer — needs to pass through the same UUID() constructor to become MongoDB's native BSON UUID type. Use the sql server uuid guide to implement SQL Server GUIDs with Entity Framework Core and Dapper ORM.

mongosh
const id = UUID("550e8400-e29b-41d4-a716-446655440000");
print(id);
// Output: UUID("550e8400-e29b-41d4-a716-446655440000")

// Convert it back to a plain string
print(id.toString());
// Output: "UUID('550e8400-e29b-41d4-a716-446655440000')"

Explanation

Other Options for Generating UUIDs in MongoDB

The mongosh shell is convenient for testing, but production documents are almost always inserted from application code, so drivers expose their own way to create a MongoDB UUID.

Node.js
const { MongoClient, UUID } = require('mongodb');
const crypto = require('crypto');

// Generate a UUID with Node's built-in crypto module, then
// wrap it as MongoDB's BSON UUID (Binary subtype 4) type
const id = new UUID(crypto.randomUUID());

await db.collection('users').insertOne({ _id: id, name: 'Ada Lovelace' });

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!