Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 39/ 160
02. SQL & Data Engineering Basics

NoSQL Databases (MongoDB Basics)

Document stores, flexible schemas, and when MongoDB beats rigid relational tables.

IntermediateDocuments · Collections3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

A find from Python

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.

Key takeaway: Model by access pattern, index filter fields, flatten with json_normalize.

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.

Handling schema drift when flattening

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.

Key takeaway: Pipelines for in-database analysis; export to a warehouse for serious analytics; expect schema drift.

How it works, step by step

Step 1 of 4
Explore

1. Understand the document shape

Sample documents, list fields and types, and note nested arrays and optional fields.

db.events.find().limit(5)
Key numbers at this step
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

MongoDB (documents)
Best for: Evolving, nested data read as whole objects

Strengths: Flexible schema; natural JSON mapping; fast document reads.

Watch out: Weak at multi-collection joins and heavy analytics.

Relational database
Best for: Structured data with relationships and constraints

Strengths: Joins, integrity, mature SQL.

Watch out: Rigid schema changes; nested data is awkward.

Warehouse / lakehouse export
Best for: Analytics over MongoDB data

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?
Interview tip: Name the access pattern when choosing a document model. "Read together, store together" is the heuristic interviewers want.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply NoSQL Databases (MongoDB Basics) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
ETL vs ELT Pipelines
Next topic
Big Data Processing with PySpark