Document IDs and Primary Keys
What you'll learn: How documents are uniquely identified in document stores and what serves as their primary key.
The Core Concept
Just like every row in a relational database needs a primary key to distinguish it from all others, every document in a document store must have a unique identifier. This identifier is called the document ID and serves as the document's primary key.
Unlike relational databases where you typically define a primary key column explicitly, document stores handle this differently: the document ID is often auto-generated by the database itself, or you can provide your own application-defined ID when inserting a document.
How Document IDs Work
Think of document IDs like street addresses. Each house (document) needs a unique address (ID) so mail can be delivered to the right place. Without it, chaos ensues.
When you insert a document without specifying an ID, the database generates one automatically—typically a long, unique string or number. When you do specify an ID, you take responsibility for ensuring it's unique.
The document ID is how you:
- Retrieve a specific document directly
- Update or delete that exact document
- Reference documents from other documents (similar to foreign keys, though not enforced)
Unlike relational databases, you don't define compound primary keys or unique constraints across multiple fields—the document ID is the only guaranteed unique identifier at the database level.
Practical Implications
Auto-generated IDs provide convenience and guarantee uniqueness. Application-defined IDs give you control—useful when you have natural keys like user_email or order_number that should be unique anyway.
Key Takeaway: Every document in a document store has a unique document ID that serves as its primary key, either auto-generated by the database or explicitly set by your application, enabling direct and efficient document retrieval.