Glossary
MongoDB
A document database for data that makes sense as cohesive documents. Flexibility only helps when it is accompanied by a deliberate schema and indexes.
Short definition
A document is both a unit of data and an important design boundary.
MongoDB belongs to the family of document-oriented databases. Its basic record is not a row divided into a fixed set of columns, but a BSON document composed of fields and values. BSON is a binary representation similar to JSON, but it supports additional types such as dates, binary data, ObjectId, and Decimal128. A document is therefore not merely a JSON file stored on disk.
Documents with a similar purpose are stored in collections. A collection partly resembles a SQL table, but its documents can have different fields and nested structures. Every document in a standard collection has a unique `_id` field; if the application does not provide it, the driver or server usually creates an ObjectId. Structural flexibility is a feature, not an excuse for missing rules.
The problem it solves
Related data can be read and changed as one unit.
MongoDB is useful when the boundary of a business object naturally matches a document and the application knows its main access patterns.
- a product catalogue with attributes that vary across categories
- a user profile or settings usually read as a single unit
- content documents with nested blocks and a versioned structure
- telemetry or events when volume, retention, and queries fit the model
- API applications whose data model is genuinely document-oriented, not merely because a response uses JSON
Practical example
A product with attributes and a bounded list of variants
An online store sells products whose attributes differ by category. The name, category, attributes, and a small number of variants are loaded together on the product detail page, so they can form one document. The category is a reference because it exists independently and can be shared by many products. An index supports a specific filter by category and colour.
The `variants` array must not grow without a bound. If a product had hundreds of thousands of independently updated offers, a separate collection with a reference would be more natural. As with any database index, the benefit of a compound index should be verified against real queries; every additional index consumes space and makes writes more expensive.
MongoDB Shell (mongosh)
db.products.insertOne({
_id: ObjectId("66b100000000000000000001"),
sku: "SHOE-42",
name: "Trail Runner",
categoryId: ObjectId("66b200000000000000000001"),
attributes: { color: "blue", material: "mesh" },
variants: [
{ sku: "SHOE-42-43", size: 43, price: Decimal128("2490.00"), stock: 7 },
{ sku: "SHOE-42-44", size: 44, price: Decimal128("2490.00"), stock: 3 }
]
});
db.products.createIndex({ categoryId: 1, "attributes.color": 1 });
db.products.find(
{ categoryId: ObjectId("66b200000000000000000001"), "attributes.color": "blue" },
{ name: 1, variants: 1 }
);
How it works
From an access pattern to the resulting document
Text alternative to the diagram: application requirements determine the document boundary, the document is stored in a collection, a query uses a suitable index, and an aggregation pipeline may derive a summary.
- Access patterns First describe what the application reads together, what it changes atomically, and how the data can grow.
- Document Related values are embedded in a BSON document or connected by a reference to another document.
- Collection The document is stored in a collection where `_id` provides its unique identity.
- Query and index A filter, projection, and sort select data; a matching index can avoid an expensive collection scan.
- Aggregation A pipeline composes stages such as filtering, unwinding an array, grouping, and computing a result.
Main principles
The model is designed around operations, not around similarity to JSON responses.
A document model has its own rules for integrity, relationships, and operations.
Embedding and references
Embedding keeps related data inside one document so it can be read and changed together. A reference stores the identifier of another document and suits independently existing entities, complex relationships, or unbounded collections of values. MongoDB can join data in aggregation through `$lookup`, but that is not a reason to copy a relational model without thought.
Flexible schema and validation
By default, documents in a collection do not need to have the same fields or types. The application still has a schema and must handle its evolution. Schema validation can use rules including `$jsonSchema` to check required fields, BSON types, or ranges and reject an invalid write by default.
Atomic operations and transactions
A write to one document is atomic, which supports well-chosen embedding boundaries. When one business change spans several documents, collections, or shards, MongoDB supports multi-document transactions. They cost more and do not replace a sound model or a deliberate transaction boundary.
Replication and sharding
A replica set maintains copies of data on several nodes and can elect a new primary after a failure. Sharding distributes collection documents across shards by a shard key when data or load exceeds one node. Both capabilities add operational decisions; sharding is not a default optimisation for a small application.
Benefits and limitations
The benefit depends on whether a document matches the business boundary.
Potential benefits
- reading related data in one operation with appropriate embedding
- an atomic change to an entire single document
- flexible document evolution complemented by targeted validation
- queries and aggregation over nested fields and arrays
Limitations and common mistakes
- unbounded embedded arrays and repeated rewrites of large documents
- ignoring indexes, query selectivity, and write cost
- uncontrolled duplication that creates diverging copies of data
- choosing MongoDB only because a REST API transfers JSON
Comparison and scope of use
MongoDB is not automatically faster or simpler than a relational database.
For a catalogue with varying attributes and predictable whole-product reads, a document model can simplify the work. Duplication, such as a copy of the displayed category name, can be a deliberate read optimisation. There must still be a process that updates copies after their source changes and can detect divergence. Performance is evaluated for a specific model, indexes, volume, and workload.
If a domain relies on many relationships, foreign keys, uniqueness rules across entities, complex ad hoc queries, and frequent transactions spanning multiple records, a relational model in PostgreSQL or MySQL may be more natural. This is not a database ranking: the right choice follows from invariants, access patterns, operational knowledge, and migration risks.
What to keep in mind
A document model is a concrete architectural decision.
Before deployment, verify not only a sample insert, but also growth, concurrency, and recovery.
- document the main queries, writes, and business boundaries before choosing embedding
- apply schema validation to critical fields and safely version structural changes
- measure query plans and design compound indexes around real filters and sorting
- bound the size and cardinality of arrays inside a document; a BSON document has a maximum size of 16 MiB
- test concurrent changes, backups, recovery, and driver behaviour during a transient failure
Common questions
What a flexible document model means in practice
Is MongoDB a schemaless database?
No. It allows a flexible document structure by default, but the application has a data model and MongoDB supports schema validation for types, required fields, and other rules.
Does MongoDB support transactions?
Yes. Operations on one document are atomic and transactions are available for changes across multiple documents, collections, databases, or shards. Their operational cost does not replace an appropriate model.
When should data be embedded and when should it be referenced?
Embedding suits data read and changed together with bounded growth. A reference is more suitable for independent entities, complex relationships, frequent independent changes, or unbounded cardinality.
Is MongoDB automatically better for a JSON API?
No. An API transfer format does not determine the right persistence model. Relationships, integrity rules, queries, update patterns, and operational experience decide.
Do aggregations replace relational SQL queries?
An aggregation pipeline can filter, transform, group, and join documents, but it has a different model and trade-offs. Database design should not be based on a mechanical rewrite of SQL.
Personal experience
I choose a database around data, operations, and operational boundaries.
In e-commerce projects, I connect data modelling with integrity, indexes, migrations, and measurement of real queries.