Documents & Collections
Understand the structure of a MongoDB document, the _id field, and how documents group into collections.
Anatomy of a Document
A document is a set of field-value pairs, similar to a JSON object. Values can be strings, numbers, booleans, dates, arrays, nested documents (embedded objects), or null.
{ "_id": ObjectId("64f1a2b3c4d5e6f7a8b9c0d1"), "title": "Getting Started with MongoDB", "published": true, "views": 1420, "tags": ["database", "nosql", "mongodb"], "author": { "name": "Ada Lovelace", "email": "ada@example.com" }, "createdAt": ISODate("2026-01-15T10:00:00Z")}The _id Field
Every document requires a unique _id field, serving as its primary key. If you don't provide one when inserting, MongoDB automatically generates an ObjectId — a 12-byte identifier that encodes a timestamp, making documents naturally sortable by creation time.
Because the first four bytes of an ObjectId represent its creation time, sorting documents by _id also roughly sorts them by insertion order — a useful, often-overlooked property.
Collections
A collection groups related documents together — roughly analogous to a table, but without a fixed schema enforced by default. A typical application database might have collections named users, posts, and orders.
use blog_app;db.posts.insertOne({ title: "My First Post" }); // creates the "posts" collection if it doesn't existDocuments Can Vary in Shape
Unlike a SQL table, two documents in the same collection are not required to share the same fields — a deliberate flexibility that's powerful, but requires discipline in application code to handle gracefully.
// Both valid documents in the same "products" collection{ "_id": 1, "name": "T-Shirt", "size": "M", "color": "blue" }{ "_id": 2, "name": "Laptop", "cpu": "M3", "ram": "16GB" }Common Beginner Mistakes
MongoDB enforces uniqueness on _id automatically — attempting to insert a duplicate throws an error, which is exactly the intended safeguard.
Application code still needs consistent expectations about document shape — the schema design lessons cover disciplined, deliberate approaches to this.
FAQs
Yes — any unique value (a string, a number) works as _id, though ObjectId's built-in uniqueness and timestamp encoding make it the sensible default for most cases.
Yes — 16MB per document, a limit that reinforces MongoDB's general design philosophy of documents representing one cohesive, not-too-large unit of data.
Summary
Documents are flexible, self-contained JSON-like records identified by a unique _id, grouped into collections. Next, you'll look closer at BSON and the specific data types MongoDB supports.