MongoDB Fundamentals

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

If you have not yet installed MongoDB, consider completing the Installation & Project Setup tutorial first.

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.

MongoDB Server
Database: shopDB
Collection: products
Collection: orders
Document
Document
Document

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 shopDB

Note

A database is only actually created once you insert at least one document into a collection within it.

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 🔍

AspectJSONBSON
FormatText-basedBinary
Data TypesLimited (string, number, boolean, etc.)Extended (Date, ObjectId, Binary, and more)
Parsing SpeedSlower for machinesFaster to parse and traverse
Human ReadabilityHighLow (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

Embedding works best for data that is bounded in size and rarely needs to be queried independently of its parent document.

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 _id

ObjectId 🆔

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

Model data based on query patterns first, and normalize only when duplication or document growth becomes a real problem.

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

Flexibility can lead to inconsistent data if not paired with application-level validation or MongoDB's schema validation rules.

Collections vs Tables 🆚

AspectCollection (MongoDB)Table (SQL)
SchemaFlexibleFixed columns
Structure EnforcementOptional (via validation rules)Enforced by table definition
Row/Document UniformityNot requiredRequired

Documents vs Rows 🆚

AspectDocument (MongoDB)Row (SQL)
StructureNested, hierarchicalFlat, columnar
Related DataOften embedded directlySplit across related tables
FormatBSONTable-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.

Replica Set
Primary Node (handles writes)
Secondary Node (replicates data)
Secondary Node (replicates data)

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

Prior to WiredTiger, MongoDB used the MMAPv1 storage engine, which has since been deprecated.

CRUD Overview 🔁

Every interaction with MongoDB data falls into one of four fundamental operations, collectively known as CRUD: Create, Read, Update, and Delete.

OperationExample Method
CreateinsertOne(), insertMany()
Readfind(), findOne()
UpdateupdateOne(), updateMany()
DeletedeleteOne(), 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

Reading from secondary nodes can improve read throughput but may return slightly stale data due to replication lag.

Best Practices ✅

  1. Design documents around your application's access patterns, not abstract normalization rules.
  2. Keep documents within a reasonable size to avoid hitting the 16MB document size limit.
  3. Use schema validation for collections where data consistency is critical.
  4. Prefer ObjectId as _id unless there is a clear reason to use a custom identifier.

Common Mistakes âš ī¸

  1. Embedding unbounded arrays that grow indefinitely, risking oversized documents.
  2. Assuming a dynamic schema means no design is necessary at all.
  3. Overusing references, resulting in excessive $lookup operations that hurt performance.
  4. Ignoring the implications of eventual consistency when reading from secondary nodes.

Frequently Asked Questions ❓

Question

Is the _id field required?

Answer

Yes, every document must have one; MongoDB will automatically generate an ObjectId if you don't supply one.

Question

Can two documents in the same collection have different fields?

Answer

Yes, MongoDB's dynamic schema allows this by default, though schema validation rules can restrict it if needed.

Question

What is the maximum size of a single document?

Answer

The maximum BSON document size is 16 megabytes.

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.