# What Is MongoDB? The Document Model, Sharding and When to Use It

> MongoDB is a non-relational document database using BSON for flexible data storage, offering horizontal scalability and high availability for modern apps.

Source: https://camnangai.com/en/engineering/what-is-mongodb  
Published: 2026-08-12

[**MongoDB**](https://www.mongodb.com) is a non-relational, document-oriented database that
stores information in a flexible, hierarchical format. Unlike a traditional relational
database (RDBMS), which relies on rigid row-and-column structures, MongoDB uses BSON (Binary JSON) to
represent data. This binary format allows self-describing documents where fields can vary across
records in the same collection, which supports rapid, iterative development and maps naturally onto
modern object-oriented programming.

MongoDB is built for high throughput and horizontal scalability. BSON lets the database support
advanced data types that standard JSON cannot natively handle, including Decimal128, 64-bit integers,
and high-precision timestamps — so the data layer keeps the same shape as your application code while
staying efficient to store and fast to read.

The platform keeps evolving on the query-planning side. Starting in MongoDB 8.3, multi-planning with
a Cost-Based Ranker (CBR) backup is the default plan selection mechanism for eligible queries: the
multi-planner first attempts to find a plan that returns a result set within a short trial period,
and only if that fails does MongoDB apply a set of rules to decide whether to continue multi-planning
or let CBR evaluate each node in the plan. Version 8.3 also improves array processing, letting you
access element indexes inside `$map`, `$filter`, and `$reduce` expressions through the new
`arrayIndexAs` field or the `$$IDX` system variable.

Flexible schemas are what separate MongoDB from the world of fixed tables and rows.

![MongoDB, the NoSQL document database that stores information as flexible documents instead of rigid rows and columns](https://camnangai.com/articles/mongodb-la-gi/01-infographic-en.webp)

## What is MongoDB?

**MongoDB** is a document database where the document is the fundamental unit of data storage.
Related documents are grouped into collections, which work like tables but do not enforce a uniform
schema. Data is stored in BSON, a binary encoding of JSON that carries more type information than a
text format can. BSON's support for specialized types like 64-bit integers and specific date formats
allows precise computation and sorting without the error-prone manual conversion that standard JSON
requires.

![MongoDB's hierarchy: documents live inside collections, collections live inside a database, and data is stored on disk as BSON](https://camnangai.com/articles/mongodb-la-gi/02-en.webp)

Every document requires a unique identifier in the mandatory `_id` field. While MongoDB can
auto-generate a 12-byte ObjectId, engineers often provide explicit values to reduce index overhead.
Developers interact with the cluster using the MongoDB Query API to perform CRUD (Create, Read,
Update, Delete) operations, which support complex filtering on nested arrays and objects.

```json
{
  "_id": 1,
  "first_name": "Tom",
  "email": "tom@example.com",
  "cell": "765-555-5555",
  "likes": ["fashion", "spas", "shopping"],
  "businesses": [
    {
      "name": "Entertainment 1080",
      "partner": "Jean",
      "status": "Bankrupt",
      "date_founded": { "$date": "2012-05-19T04:00:00Z" }
    },
    {
      "name": "Swag for Tweens",
      "date_founded": { "$date": "2012-11-01T04:00:00Z" }
    }
  ]
}
```

## How does the document model differ from relational tables?

The main difference between **MongoDB** and an RDBMS like MySQL is that documents nest and tables are
flat. In a relational database, normalization breaks data apart, so putting it back together takes
expensive multi-table JOINs. MongoDB operates on the
principle that data accessed together should be stored together, prioritizing read performance and
reducing I/O by nesting related data inside a single document.

![The document model versus relational tables: one nested document read in a single pass, contrasted with several SQL tables that must be JOINed together](https://camnangai.com/articles/mongodb-la-gi/03-en.webp)

While an RDBMS prioritizes **referential integrity** through strict schema enforcement and foreign
keys, MongoDB trades that for **horizontal scalability** and development velocity. Schema flexibility
allows polymorphism — documents in the same collection holding different fields — which moves you
from a rigid migration-driven approach to an iterative one. That matters most in large-scale
production environments, where locking tables for a schema change is not feasible.

## Querying and aggregating data in MongoDB

The Aggregation Pipeline is a multi-stage framework that runs sophisticated data processing directly
on the cluster, avoiding the latency of moving large datasets to an external analytics platform. It
transforms documents as they pass through successive stages, offering far more depth than
single-purpose methods like `distinct()` or `estimatedDocumentCount()`.

![The Aggregation Pipeline: data flowing through the match, unwind, group, sort and limit stages to a final result](https://camnangai.com/articles/mongodb-la-gi/04-en.webp)

Common stages include:

- **$match**: Filters documents against specific criteria to reduce the working set.
- **$unwind**: Deconstructs array fields, outputting one document per element.
- **$group**: Aggregates documents by a key to compute results like `$sum` or `$avg`.
- **$sort** and **$limit**: Order and restrict the final output for efficiency.

```javascript
// Finding top 3 directors by movie count using the sample_mflix dataset
db.movies.aggregate([
  { $match: { directors: { $exists: true, $ne: null, $not: { $size: 0 } } } },
  { $unwind: "$directors" },
  { $group: { _id: "$directors", movieCount: { $sum: 1 } } },
  { $sort: { movieCount: -1 } },
  { $limit: 3 },
]);
```

## Replica sets, sharding, and ACID transactions

To deliver high availability and scale, **MongoDB** uses two complementary mechanisms. A **replica
set** is a group of servers maintaining identical copies of the data, providing redundancy and
automatic failover. **Sharding** provides horizontal scaling by distributing data across multiple
clusters, or shards. A shard is itself typically a replica set, so the system achieves massive scale
and high availability at the same time.

![A replica set with one Primary and several Secondaries holding identical copies, and sharding splitting data across shards for horizontal scale](https://camnangai.com/articles/mongodb-la-gi/05-en.webp)

While the document model minimizes the need for cross-document operations, MongoDB supports
multi-document **ACID transactions**, which keep complex operations across several collections safe.
From an efficiency standpoint, though, distributed transactions cost more than single-document atomic
writes — and those single-document writes remain the target a good schema design aims for.

## Schema design: embed or reference?

Deciding whether to embed (denormalize) or reference (normalize) data is the biggest decision in
**MongoDB** modeling.

![Schema design in MongoDB: embedding versus referencing, the two choices driven by the application's access pattern](https://camnangai.com/articles/mongodb-la-gi/06-en.webp)

| Feature            | Embedding                              | Referencing                      |
| :----------------- | :------------------------------------- | :------------------------------- |
| **Relationship**   | One-to-few (e.g. user and 3 addresses) | One-to-many or one-to-millions   |
| **Data growth**    | Small and bounded                      | Likely to grow unbounded         |
| **Access pattern** | Data is always read together           | Data is accessed independently   |
| **Consistency**    | Atomic updates for all fields          | Trades atomicity for flexibility |

Beyond these, engineers reach for patterns like the **Subset Pattern**, which stores the most recent
related data — the latest 5 reviews, say — in the parent document while keeping the full history in a
separate collection. For time-series data, the **Bucket Pattern** groups readings by hour into a
single document to cut the total document count and improve index efficiency. Modeling should also
account for **temporal data**, where preserving a historical value — a shipping address as it stood
at the time of an order — matters even after the parent record changes.

## Common data modeling mistakes

Poor design leads to working-set bloat and I/O bottlenecks:

- **Unbounded arrays**: embedding arrays that grow indefinitely will eventually hit the 16MB BSON
  document size limit, and performance falls off long before that.
- **Over-normalization**: leaning too heavily on `$lookup` throws away the performance benefit of the
  document model in the first place.
- **The small document problem**: in collections of very small documents, the overhead of field names
  and the identifier gets disproportionately large. Use shorter field names, and store useful
  unique data such as a SKU or UUID in the `_id` field explicitly. Because MongoDB **always indexes**
  `_id`, putting real data there saves the storage and memory cost of a second index.

![The unbounded array mistake: an embedded array growing until it hits the 16 MB ceiling of a single document](https://camnangai.com/articles/mongodb-la-gi/07-en.webp)

## Self-managed or MongoDB Atlas?

You can run a self-managed edition — Community or Enterprise — or use **MongoDB Atlas**, a fully
managed multi-cloud platform. Atlas automates deployment, backups, and security across AWS, GCP, and
Azure.

Its main advantages are continuous performance monitoring, automated scaling of cluster tiers, and
built-in security features like network isolation and IP whitelisting. Setting Atlas up means
configuring **Database Access** for user roles and **Network Access** for IP whitelisting. For
early-stage testing, Atlas offers a free tier (M0) capped at 512MB of storage.

## When should you choose MongoDB?

**MongoDB** earns its place where you need a flexible schema, high write throughput, and horizontal
scale — IoT and time-series workloads, product catalogs, real-time analytics. By mapping data
directly onto modern programming objects, it removes the overhead and complexity of an ORM layer, and
it lets the data model evolve without the disruption of frequent schema migrations.

![When to choose MongoDB and when a relational database is still the better fit](https://camnangai.com/articles/mongodb-la-gi/08-en.webp)

What it gives up for that scale is the strict referential integrity an RDBMS enforces on your behalf.
If your workload leans on constraints spanning many entities, and on transactions that cross them, a
relational database is still the better fit — so make that trade knowingly rather than by default.

## References

- [What is MongoDB? - Database Manual - MongoDB Docs](https://www.mongodb.com/docs/manual/introduction/)
- [Document Database - NoSQL | MongoDB](https://www.mongodb.com/resources/basics/databases/document-databases)
- [What Is NoSQL? NoSQL Databases Explained | MongoDB](https://www.mongodb.com/resources/basics/databases/nosql-explained)
- [Comparing The Differences - MongoDB Vs MySQL | MongoDB](https://www.mongodb.com/resources/compare/mongodb-mysql)
- [Aggregation Operations - Database Manual - MongoDB Docs](https://www.mongodb.com/docs/manual/aggregation/)
- [Best Practices for Data Modeling in MongoDB - Database Manual - MongoDB Docs](https://www.mongodb.com/docs/manual/data-modeling/best-practices/)
- [How to Design MongoDB Schemas for Real-World Applications](https://oneuptime.com/blog/post/2026-02-20-mongodb-schema-design-patterns/view)
- [Introduction to MongoDB Atlas - GeeksforGeeks](https://www.geeksforgeeks.org/mongodb/what-is-mongodb-atlas/)
- [Release Notes for MongoDB 8.3 - Database Manual - MongoDB Docs](https://www.mongodb.com/docs/manual/release-notes/8.3/)
