Databases
MongoDB
The most popular document NoSQL database, storing data as JSON-like documents (BSON).
What it is
MongoDB stores data as documents in collections, not rows in tables. A document has a flexible structure, can hold nested objects and arrays, and the schema can change without migrations.
It has a rich query language and aggregation pipeline, indexes, multi-document transactions, replication (replica sets) and sharding for horizontal scaling. Atlas is the managed cloud version.
The SSPL license is not open source by the OSI definition: cloud providers cannot offer it as a service without conditions. Using it inside your own application has no restrictions.
Use it when
- Data with a changing structure: catalogs, content, profiles.
- A fast prototype where the schema still evolves.
- You need horizontal scaling with sharding.
Avoid it when
- Many relations between entities and complex joins: a relational database.
- Strict financial invariants across many tables.
Key concepts
- Document / Collection
- A BSON document and a group of documents.
- Aggregation pipeline
- A sequence of stages like
$match,$group,$lookup. - Replica set
- A group of nodes with one primary and replicas.
- Sharding
- Spreading a collection across nodes by a shard key.
Example
Cheat sheet
| Command or code | What it does |
|---|---|
mongosh "mongodb://localhost:27017" | Connect to the server |
use shop | Select a database (created on first write) |
db.users.insertOne({ name: "Ann", age: 30 }) | Insert a document |
db.users.find({ age: { $gt: 25 } }) | Find documents by a condition |
db.users.updateOne({ name: "Ann" }, { $set: { age: 31 } }) | Update a field in a document |
db.users.deleteOne({ name: "Ann" }) | Delete one document |
db.users.createIndex({ email: 1 }, { unique: true }) | Unique index on a field |
db.users.find({ age: 30 }).explain("executionStats") | Query plan and statistics |
db.orders.aggregate([{ $match: { paid: true } }, { $group: { _id: "$userId", sum: { $sum: "$total" } } }]) | Aggregation: order total per user |
mongodump --db shop --out ./backup | Back up a database |
How to learn it
- Understand the document model: collections, BSON documents, when it beats tables and when it does not.
- Run MongoDB in Docker or Atlas and connect with
mongoshor Compass. - Learn CRUD:
insertOne,find,updateOne,deleteOneand the operators$set,$inc,$push. - Learn filters and projections:
$gt,$in,$and,$regex, plus sorting and pagination. - Design a schema: embed or reference, and why that depends on access patterns.
- Add indexes (single and compound), read
explain()and remove slow collection scans. - Write an aggregation pipeline with
$match,$group,$lookup,$sort. - Learn replica sets, transactions and connecting through a driver or Mongoose.
Interview questions
1. When to embed documents and when to reference?
Embed data that is read together and has bounded size. Use references for large, shared or frequently changing entities.
2. Does MongoDB support transactions?
Yes, multi-document ACID transactions exist since version 4.0. Still, the document model usually lets you rely on atomic operations on a single document.
3. What is a shard key and why does it matter?
It is the field data is distributed by across shards. A bad key causes load skew (a hot shard) and slow scatter-gather queries.
Interview questions from the bank
- Design MongoDB collections for a blog: posts, authors, comments (up to 200 thousand on a popular post), tags. What do you embed in a document, what do you reference and what antipatterns stop you?MiddleDatabases
- Query:
db.orders.find({ status: 'paid', total: { $gt: 100 } }).sort({ createdAt: -1 }).limit(20). Which compound index do you create? Explain the ESR rule and how to check withexplain.MiddleDatabases - Explain write concern and read concern in a MongoDB replica set. What happens to a
w:1write after a failover? How do you get read your writes when reading from a secondary?SeniorDatabases - MongoDB supports multi document transactions. Why does the documentation advise against building the data model on them? What does a transaction cost, which errors must be handled and how do you do without one?SeniorDatabases
- A candidate says: PostgreSQL is CA, MongoDB is CP, Cassandra is AP. What is wrong with that claim? Explain CAP and PACELC in a way that helps configure a real system.SeniorDatabases
Comparisons with this technology
Related technologies
- PostgreSQLA powerful open source relational database with extensions, JSONB, full-text search and strong SQL support.
- Amazon DynamoDBA fully managed AWS key-value and document database with predictable latency and automatic scaling.
- Apache CassandraA distributed wide-column database with no single point of failure, built for massive write volumes.
- PrismaAn ORM for Node.js and TypeScript with a schema file, a generated type-safe client and migrations.
- ElasticsearchElasticsearch is a distributed search and analytics engine built on Lucene with a REST API and JSON documents.
Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).