Course Outline (Part 4)

Before writing code or running queries, it is crucial to understand the fundamental building blocks of MongoDB. If you don’t grasp the core terminology, reading MongoDB documentation or discussing architecture with other developers will feel like reading a foreign language.

In this module, we will demystify the core concepts: Databases, Collections, Documents, and BSON, followed by a look at how MongoDB servers operate together in the real world.


What is a Database?

In MongoDB, a Database is simply a physical container for data. Each database gets its own set of files on the file system.

A single MongoDB server (or cluster) can host multiple databases simultaneously. For example, if you are running a server for your startup, you might have one database named production_ecommerce, another named testing_ecommerce, and a third named employee_blog.

They are completely independent of each other. Querying data in one database does not affect or interact with data in another database unless explicitly configured to do so.


What is a Collection?

Inside a database, data is grouped into Collections.

A Collection is the MongoDB equivalent of an SQL Table. If you are building a school management system, you might have a database called school_db that contains the following collections:

  • students
  • teachers
  • classes
  • grades

The Schema-less Magic: Unlike an SQL Table, a Collection does not enforce a schema. In a relational database, every row in a table must have the exact same columns. In a MongoDB collection, the data is entirely flexible.

For instance, in the students collection, one student might have a dormRoom field, while another student simply doesn’t have that field. MongoDB doesn’t care—it happily stores them both in the same collection.


What is a Document?

A Document is a single record of data inside a Collection. It is the MongoDB equivalent of an SQL Row.

Documents are represented as JSON objects—a simple list of key-value pairs. Here is an example of what a Document inside the students collection might look like:

{
  "_id": ObjectId("5099803df3f4948bd2f98391"),
  "firstName": "John",
  "lastName": "Doe",
  "age": 22,
  "majors": ["Computer Science", "Mathematics"],
  "address": {
    "city": "Boston",
    "state": "MA"
  }
}

Notice the _id field at the very top. Every document in MongoDB must have a unique _id field. It acts as the Primary Key. If you do not provide an _id when you insert a document, MongoDB will automatically generate a highly unique ObjectId for you.


BSON Explained

We keep mentioning that MongoDB stores data as JSON (JavaScript Object Notation). While this is true from a developer’s perspective, under the hood, MongoDB actually stores data as BSON.

BSON stands for Binary JSON.

When you send a JSON document to MongoDB, the database engine compiles it down into a highly optimized binary format before saving it to the hard drive.

Why bother doing this? Because parsing plain-text JSON is incredibly slow for a computer. Reading a binary file is exponentially faster. Furthermore, BSON is highly traversable, allowing MongoDB to skip over fields it doesn’t need when searching for specific data.


JSON vs BSON

If BSON is just Binary JSON, what are the actual differences?

  1. Speed & Size: BSON is machine-readable, making it incredibly fast for the database to parse, search, and retrieve.
  2. Data Types: Standard JSON is very limited in the data types it supports (String, Number, Boolean, Array, Object, Null). BSON adds several crucial data types specifically for databases, including:
    • Date (Proper datetime objects, not just strings)
    • ObjectId (MongoDB’s unique 12-byte identifiers)
    • Decimal128 (High-precision decimals for financial data)
    • Binary Data (For storing small images or files)

When you query MongoDB, it instantly translates the BSON back into human-readable JSON so you can interact with it effortlessly in your code. You get the speed of binary with the ease of JSON!


MongoDB Architecture (High Level)

Now that you know how data is structured, let’s look at how the actual servers are structured in a production environment.

You should never run a critical production application on a single MongoDB server. If that single computer crashes, or the hard drive fails, your entire application goes offline, and your data could be lost forever.

To solve this, MongoDB uses an architecture called Replica Sets.


Replica Sets Overview

A Replica Set is simply a group of MongoDB servers (minimum of three) that all maintain the exact same dataset. They work together as a team to ensure High Availability. If one server dies, the database continues running without a single second of downtime.

Here is how the team operates:

Primary Node

In every Replica Set, there is exactly one Primary Node.

  • The Primary Node is the boss.
  • It is the only server that can accept Write operations (insert, update, delete).
  • Every time data is written to the Primary Node, it records the operation in a special log called the oplog (Operation Log).

Secondary Nodes

The other servers in the group are called Secondary Nodes.

  • They are constantly copying the oplog from the Primary Node and applying the changes to their own data.
  • They maintain an exact, real-time mirror image of the Primary Node’s data.
  • While they cannot accept Write operations, they can be configured to accept Read operations, which is a great way to distribute heavy traffic!

The Election Process (Failover)

What happens if the Primary Node unplugs or catches on fire?

The Secondary Nodes communicate with each other continuously (using “heartbeat” pings). If they stop receiving heartbeats from the Primary Node, they realize it has died.

Within seconds, the Secondary Nodes hold an Election. They vote amongst themselves to decide which Secondary Node has the most up-to-date data. The winner is instantly promoted to be the new Primary Node, and the application continues writing data to the new boss without human intervention.

When the dead server is finally rebooted, it automatically joins the team as a Secondary Node and begins copying data to catch up!


Summary

You now understand the core anatomy of MongoDB!

  • Data is stored as BSON Documents.
  • Documents are grouped into schema-less Collections.
  • Collections live inside Databases.
  • Databases run on Replica Sets (Primary and Secondary nodes) for ultimate reliability.

In Module 4, we will finally open the terminal, launch the MongoDB Shell, and learn how to interact directly with the database!

Discussion

Loading comments...