Introduction đą
This tutorial explores the core building blocks of MongoDB â the concepts you will encounter in every MongoDB application, regardless of size or complexity. You will learn how databases, collections, and documents relate to one another, how data is physically represented as BSON, and how to think about schema design in a system that does not enforce a fixed structure. These fundamentals form the foundation for everything else you will do with MongoDB.
Information
How MongoDB Works âī¸
MongoDB organizes data in a simple hierarchy: a server hosts one or more databases, each database contains one or more collections, and each collection holds many documents. When your application performs a query, MongoDB locates the relevant collection and uses indexes, if available, to efficiently find matching documents rather than scanning every record.
Databases đī¸
A database is the top-level container for related collections. A single MongoDB server can host multiple databases, each isolated from the others, making it easy to separate data for different applications or environments.
Switching databases in mongosh
use shopDBNote
Collections đ
A collection groups related documents together, similar to a table in a relational database. Collections have no fixed schema by default, meaning documents inside the same collection can have different fields and structures.
Creating a collection explicitly
db.createCollection("products");Documents đ
A document is the fundamental unit of data storage in MongoDB, represented internally as BSON but conceptually equivalent to a JSON object. Documents consist of field-value pairs and can contain nested structures.
Example document
{
"_id": 101,
"name": "Wireless Mouse",
"price": 19.99,
"inStock": true
}BSON đ§Ŧ
BSON (Binary JSON) is the binary-encoded format MongoDB uses to store documents. It extends the JSON model with richer data types and is designed to be fast to scan and traverse, which improves both storage efficiency and query performance.
JSON vs BSON đ
| Aspect | JSON | BSON |
|---|---|---|
| Format | Text-based | Binary |
| Data Types | Limited (string, number, boolean, etc.) | Extended (Date, ObjectId, Binary, and more) |
| Parsing Speed | Slower for machines | Faster to parse and traverse |
| Human Readability | High | Low (binary) |
Document Structure đī¸
Documents are structured as an ordered set of key-value pairs. Values can be simple types like strings and numbers, or more complex structures such as nested documents and arrays.
A more complex document structure
{
"_id": 202,
"name": "Laptop",
"specs": {
"cpu": "Octa-core",
"ramGB": 16
},
"tags": ["electronics", "computers"]
}Embedded Documents đĒ
An embedded document is a document nested inside another document's field, used to model relationships where related data is frequently accessed together.
Embedded address document
{
"_id": 303,
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "Springfield",
"zip": "12345"
}
}Tip
Arrays đ
Fields can hold arrays, allowing a single document to store lists of values or even lists of nested documents.
Document with an array field
{
"_id": 404,
"title": "Introduction to Databases",
"authors": ["Jane Doe", "John Smith"],
"reviews": [
{ "user": "bob123", "rating": 5 },
{ "user": "carol99", "rating": 4 }
]
}Data Types đĸ
MongoDB's BSON format supports a rich set of data types beyond what plain JSON offers.
- String: UTF-8 text data.
- Int32 / Int64: Integer numeric values.
- Double: Floating-point numbers.
- Boolean: true or false.
- Date: Stored as milliseconds since the Unix epoch.
- ObjectId: A unique identifier commonly used for _id.
- Array and Object: For lists and nested documents.
- Null: Represents a missing or undefined value.
_id Field đ
Every document in MongoDB must have a unique _id field, which acts as its primary key within the collection. If you don't provide one when inserting a document, MongoDB automatically generates an ObjectId for you.
Inserting without specifying _id
db.users.insertOne({ name: "Dave" });
// MongoDB automatically assigns an ObjectId as _idObjectId đ
An ObjectId is a 12-byte identifier that is unique across a collection, typically encoding a timestamp, a random value, and a counter. This makes it possible to infer creation time directly from the identifier itself.
Extracting the timestamp from an ObjectId
const id = ObjectId("64f1a2b3c4d5e6f7a8b9c0d1");
print(id.getTimestamp());Database Design Basics đ§ą
Unlike relational databases, MongoDB encourages designing your schema around how your application will access and use the data, rather than strictly normalizing it. Good design typically balances read performance, write performance, and data duplication.
Schema Design đ§Š
Schema design in MongoDB revolves primarily around choosing between embedding and referencing related data, based on how frequently that data is accessed together and how large it can grow.
Best Practice
Dynamic Schema đ
MongoDB's dynamic schema means documents within the same collection are not required to share the same fields or structure, which makes it easy to evolve your data model as application requirements change over time.
Documents with differing structures in the same collection
{ "_id": 1, "name": "Alice", "age": 30 }
{ "_id": 2, "name": "Bob", "email": "bob@example.com" }Caution
Collections vs Tables đ
| Aspect | Collection (MongoDB) | Table (SQL) |
|---|---|---|
| Schema | Flexible | Fixed columns |
| Structure Enforcement | Optional (via validation rules) | Enforced by table definition |
| Row/Document Uniformity | Not required | Required |
Documents vs Rows đ
| Aspect | Document (MongoDB) | Row (SQL) |
|---|---|---|
| Structure | Nested, hierarchical | Flat, columnar |
| Related Data | Often embedded directly | Split across related tables |
| Format | BSON | Table-specific binary/text format |
MongoDB Architecture đī¸
In production, MongoDB is typically deployed as a replica set â a group of servers maintaining copies of the same data â and, for larger workloads, multiple replica sets are combined into a sharded cluster for horizontal scalability.
Storage Engine Overview đŊ
MongoDB uses a pluggable storage engine architecture, with WiredTiger as the default since MongoDB 3.2. WiredTiger provides document-level concurrency control and built-in compression, improving both performance and storage efficiency.
Reference
CRUD Overview đ
Every interaction with MongoDB data falls into one of four fundamental operations, collectively known as CRUD: Create, Read, Update, and Delete.
| Operation | Example Method |
|---|---|
| Create | insertOne(), insertMany() |
| Read | find(), findOne() |
| Update | updateOne(), updateMany() |
| Delete | deleteOne(), deleteMany() |
Data Consistency đ
MongoDB provides strong consistency for reads and writes directed at the primary node of a replica set by default. It also supports configurable read concerns and write concerns, letting developers balance consistency against performance and availability.
Information
Best Practices â
- Design documents around your application's access patterns, not abstract normalization rules.
- Keep documents within a reasonable size to avoid hitting the 16MB document size limit.
- Use schema validation for collections where data consistency is critical.
- Prefer ObjectId as _id unless there is a clear reason to use a custom identifier.
Common Mistakes â ī¸
- Embedding unbounded arrays that grow indefinitely, risking oversized documents.
- Assuming a dynamic schema means no design is necessary at all.
- Overusing references, resulting in excessive $lookup operations that hurt performance.
- Ignoring the implications of eventual consistency when reading from secondary nodes.
Frequently Asked Questions â
Question
Answer
Question
Answer
Question
Answer
Summary đ
You now understand the fundamental building blocks of MongoDB: databases, collections, and documents, along with how data is represented as BSON. You've also seen how embedding and arrays enable rich, nested data models, and how MongoDB's dynamic schema and architecture differ from traditional relational systems.
What's Next? đ
- Dive into CRUD operations in detail, including query operators and update modifiers.
- Learn how to design effective indexes for your queries.
- Explore schema design patterns for common real-world use cases.
- Study the aggregation pipeline for advanced data analysis.