NoSQL Databases (MongoDB Basics)
Document stores, flexible schemas, and when MongoDB beats rigid relational tables.
In plain words
MongoDB stores each record as a flexible nested document instead of rows in a rigid table.
Think of it like…
A filing cabinet of folders where each folder holds a customer's whole story (profile, addresses, orders) rather than spreading it over several cabinets. Folders can differ in what they contain; finding one is quick, but cross-referencing many cabinets is awkward.
Where you’ve seen it
An app stores user events as documents like {user_id: 42, ts: ..., type: 'purchase', items: [{sku: 'A1', qty: 2}, {sku: 'B7', qty: 1}], device: {os: 'iOS'}}. For analysis, a pipeline runs an aggregation: $match purchases in October, $unwind the items, $group by sku summing qty. It exports 3 million flattened rows to Parquet, where pandas and SQL can work on them. Fields added in later app versions are missing in older documents, so the pipeline treats absent values explicitly.
Words you’ll hear
- Document / collection
- A JSON-like record / a group of documents (like a table).
- Embedding vs referencing
- Nesting related data inside a document vs storing ids that point to other documents.
- Aggregation pipeline
- A sequence of stages ($match, $group, $project, …) that transform documents.
- Flexible schema
- Documents in one collection can differ; validation rules can restrict this.
Visual diagram
Theory & deep dive
Documents, queries and the data model
A document groups data that is read together: a customer with an embedded list of addresses, an order with its line items. Embedding gives fast single-document reads and atomic updates, but duplicates data if the same sub-entity appears in many documents and large arrays can grow without bound (documents are limited to 16 MB). Referencing stores ids (like foreign keys) and uses $lookup or application-side joins, which is flexible but loses the main advantage. Model around access patterns: what does the application read and write together?
Queries use JSON filters: db.events.find({type: "purchase", ts: {$gte: ISODate("2026-10-01")}}, {user_id: 1, items: 1, _id: 0}) returns matching documents with selected fields. Combine conditions with $and/$or, test membership with $in, match nested fields with dot notation ("device.os": "iOS") and arrays with $elemMatch. Indexes (single-field, compound, text, TTL) are essential: without one, a filter scans the whole collection.
docs = db.events.find({"type": "purchase", "ts": {"$gte": start}}, {"_id": 0, "user_id": 1, "items": 1}); df = pd.json_normalize(list(docs), record_path="items", meta=["user_id"]) turns the nested items array into one row per item with the user id attached.
Aggregation pipelines and when MongoDB isn't the answer
An aggregation pipeline is a list of stages. db.events.aggregate([{"$match": {"type": "purchase"}}, {"$unwind": "$items"}, {"$group": {"_id": "$items.sku", "units": {"$sum": "$items.qty"}}}, {"$sort": {"units": -1}}, {"$limit": 10}]) filters, explodes the items array, sums units per SKU and returns the top ten, all inside the server, the equivalent of WHERE, a join to the array's rows, GROUP BY and ORDER BY/LIMIT in SQL. Put $match and $project early to shrink data and use indexes.
MongoDB shines for evolving, nested data with simple access patterns. It's weaker for complex multi-table analytics (joins are limited and costly), heavy aggregations over history (warehouses are better) and strict relational integrity. For analysis, extract to a warehouse or Parquet on a schedule (change streams or batch exports), normalise types, and document the schema, since missing and inconsistently typed fields (a string in some documents, a number in others) are common. Multi-document ACID transactions exist (MongoDB 4.0+), but design to avoid needing them.
Use .get("device", {}).get("os") or json_normalize followed by df["device.os"] = df.get("device.os") so documents without a device field produce NaN rather than errors, then record how many were missing.
How it works, step by step
Step 1 of 41. Understand the document shape
Sample documents, list fields and types, and note nested arrays and optional fields.
- Check
- field presence rates
When to use it & trade-offs
What it is
MongoDB is a document database: data lives in collections of documents (JSON-like BSON objects) that can have nested fields and arrays, and different documents in a collection may have different fields (a flexible schema, optionally enforced with schema validation). Each document has a unique _id. You query with find(filter, projection) using operators such as $gt, $in and $and, and analyse with the aggregation pipeline ($match, $group, $project, $unwind, $lookup, $sort). From Python, PyMongo returns dictionaries you turn into pandas with pd.json_normalize.
Why it matters: Event logs, user profiles, product catalogues, app configuration and API payloads arrive as nested JSON, and many applications store them in MongoDB. Data scientists meet this data constantly, so they need to query it, flatten it for analysis and know when a document model suits the data and when a relational or columnar model is better. The pitfalls are schema drift, missing fields and expensive cross-collection joins.
When to reach for it
- Querying event, profile and catalogue data stored as documents
- Flattening nested JSON for modelling
- Server-side aggregation before export
When to avoid or be careful
- Unindexed filters on large collections
- Assuming every document has every field
- Heavy cross-collection joins for analytics
Document vs relational vs warehouse
Strengths: Flexible schema; natural JSON mapping; fast document reads.
Watch out: Weak at multi-collection joins and heavy analytics.
Strengths: Joins, integrity, mature SQL.
Watch out: Rigid schema changes; nested data is awkward.
Strengths: Columnar scans; joins with other sources.
Watch out: Needs a pipeline and flattening.
Interview signals & numbers to know
When this topic comes up
- “The data is in MongoDB”
- “Flatten nested JSON”
- “When would you choose NoSQL?”
- Aggregation pipelines
- Schema drift
Benchmarks & rules of thumb
- 16 MB
- maximum BSON document size
- _id
- required unique key of every document
- 4.0
- MongoDB version that added multi-document transactions
Common mistakes & follow-ups
Common interview mistakes
- Running find with no index on a 100-million-document collection.
- Assuming a field is always present and crashing on documents from an older app version.
- Using $lookup heavily for analytics instead of exporting to a warehouse.
Likely interviewer follow-ups
- When would you choose MongoDB over a relational database?
- How would you flatten nested documents for analysis?
- What's the difference between embedding and referencing?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply NoSQL Databases (MongoDB Basics) with data science interview Q&A and hands-on practice.