MongoDB

On this page 7

MongoDB is a document-oriented database system that stores data as JSON-like documents, encoded in the binary BSON format, grouped into collections rather than rows in tables. Among database systems it is the most widely used general-purpose NoSQL document store, designed for flexible schemas, developer-friendly data access and horizontal scaling.

Instead of splitting an entity across several normalized tables, MongoDB lets an application keep related data together in one document, including nested objects and arrays. It offers a rich query language, secondary indexes, an aggregation pipeline, replica sets for high availability and sharding for distributing data across servers.

The MongoDB document model

A MongoDB document is an ordered set of field and value pairs, where values can be strings, numbers, dates, binary data, arrays or embedded documents. Every document has a unique _id field, which by default is a 12-byte ObjectId containing a timestamp, and a single document may be at most 16 MB in size.

Documents live in collections, and collections live in databases. A collection does not require all documents to share the same fields, although JSON Schema validation can enforce required fields and types when consistency matters. The table below maps MongoDB concepts to their nearest relational equivalents.

MongoDB conceptRelational equivalentKey difference
DocumentRowCan nest objects and arrays
CollectionTableSchema is optional unless validated
FieldColumnMay differ between documents
Embedded documentJoined child rowStored inside the parent
$lookupJOINAvailable but used less often
Aggregation pipelineGROUP BY and viewsSequence of transformation stages
MongoDB terms and relational equivalents

How MongoDB stores and replicates data

Since version 3.2 the default storage engine is WiredTiger, which provides document-level concurrency control, compression of data and indexes, and a cache that by default uses roughly half of RAM minus 1 GB. Writes are recorded in an on-disk journal so that a crash does not lose acknowledged data.

Production deployments run as a replica set, usually three members: one primary that accepts writes and secondaries that copy its operation log, the oplog. If the primary fails, the remaining members elect a new one, typically within seconds, and drivers reconnect automatically.

Durability and consistency are tunable per operation. The following table lists the main settings and what they trade.

SettingCommon valuesEffect
Write concernw: 1, w: "majority"How many members must confirm a write
Read concernlocal, majority, snapshotWhich committed data a read may see
Read preferenceprimary, secondaryPreferredWhich member serves a read
Journalingj: trueWaits until the write reaches the journal
Consistency and durability settings

Since MongoDB 5.0 the default write concern is majority, which protects acknowledged writes from rollback after failover. Reading from secondaries reduces load on the primary but can return slightly stale data.

Querying, indexing and transactions

Queries use a document-shaped syntax, such as db.orders.find({ status: "paid", total: { $gt: 100 } }). MongoDB supports single-field, compound, multikey, text, geospatial and TTL indexes, and the same rules apply as in relational systems: without a suitable index, a query performs a full collection scan.

The aggregation pipeline processes documents through stages such as $match, $group, $sort, $project and $lookup. Placing $match early lets the pipeline use indexes and reduce data volume before expensive grouping stages.

Operations on a single document are always atomic. Since version 4.0 MongoDB also offers multi-document ACID transactions on replica sets, extended to sharded clusters in 4.2. They work, but they add latency and lock-related limits, so a good data model keeps transactions the exception rather than the rule.

MongoDB compared with other database systems

MongoDB is often weighed against relational systems such as PostgreSQL and MySQL, and against Redis for fast access. The right choice depends on data shape, consistency needs and query patterns, not on popularity.

SystemData modelStrongest fit
MongoDBDocuments in collectionsVaried, nested, evolving records
PostgreSQLRelational tables with JSONB supportComplex queries and strict integrity
MySQLRelational tablesWeb applications with stable schemas
SQLiteEmbedded relational fileLocal and mobile storage
RedisIn-memory key-value structuresCaching, sessions and counters
MongoDB versus neighboring database systems

Relational databases now store JSON well, and MongoDB now supports joins and transactions, so the gap has narrowed. MongoDB remains strongest when the application naturally reads and writes whole aggregates, such as a product with its variants or a user profile with its settings.

Data modeling decisions and common pitfalls

The central modeling choice is embedding versus referencing. Embed data that is read together and owned by the parent; reference data that is shared, large or grows without limit. Schema design in MongoDB starts from access patterns, not from normalization rules.

PitfallConsequenceRemedy
Unbounded arraysDocuments approach the 16 MB limitMove items to a separate collection
Relational design copied directlyMany $lookup stages and slow readsEmbed data read together
Missing indexesCollection scans under loadIndex fields used in filters and sorts
Poor shard keyHot shards and uneven dataChoose a high-cardinality, well-distributed key
No schema validationInconsistent field names and typesAdd JSON Schema rules to collections
Modeling pitfalls and remedies

Schema flexibility is a benefit during change but a risk over time. Without validation and code review, small inconsistencies accumulate and make queries and analytics harder than they would be in a strict schema.

Stripped to the essentials

MongoDB stores information the way people often think about it: as complete records in folders. A customer record can hold the name, the addresses and the preferences all together, instead of being cut into pieces and spread over several lists.

Records in the same folder do not need identical layouts, which makes change easy. The trade-off is that discipline must come from the team, because the database will not insist on a fixed form unless it is told to.

Where it is applied

An online marketplace sells products whose attributes differ widely: shoes have sizes and colors, laptops have processors and memory, and books have authors and page counts. In a relational design this would need many optional columns or an awkward attribute table.

The team stores each product as one MongoDB document with a shared core and a nested specs object that varies by category, plus compound indexes on category and price. Product pages load with a single indexed read, new categories need no schema migration, and a three-member replica set keeps the catalog available during server maintenance.