Skip to content

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.

Tuan Tran Van
8 min read
Contents (9 sections)
  1. What is MongoDB?
  2. How does the document model differ from relational tables?
  3. Querying and aggregating data in MongoDB
  4. Replica sets, sharding, and ACID transactions
  5. Schema design: embed or reference?
  6. Common data modeling mistakes
  7. Self-managed or MongoDB Atlas?
  8. When should you choose MongoDB?
  9. References

MongoDB 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

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

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

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

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

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

FeatureEmbeddingReferencing
RelationshipOne-to-few (e.g. user and 3 addresses)One-to-many or one-to-millions
Data growthSmall and boundedLikely to grow unbounded
Access patternData is always read togetherData is accessed independently
ConsistencyAtomic updates for all fieldsTrades 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

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

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

Share this article