Skip to main content
InterviewHubPRO
HomeTracksSection 17: MongoDB & NoSQL (50 Qs)
Section 17 of 6450 Questions (1 Per Page)

MongoDB & Document Database Architecture Master Interview Bank

WiredTiger storage engine, document modeling, aggregation framework, replica sets & raft-like consensus, sharding strategies, and write concern.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Basic & Foundational Concepts (Junior / Entry-Level)

10 Questions
1
JuniorCode#Databases & SQL

What is MongoDB and how does its Document Data Model work?

MongoDB is a leading open-source, distributed NoSQL document database: Databases: Group collections together • Collections: Similar to tables in SQL, but schema-flexible; documents in the same collection can have differing fields • Documents: JSON-like records stored on disk in BSON (Binary JSON) format (up to 16 MB per document).

2
Junior#Databases & SQL

What is BSON and why does MongoDB use BSON instead of plain JSON?

BSON is a binary serialization format for JSON-like documents: Data Types: JSON only supports String, Number, Boolean, Array, Object, Null • Traversability: BSON encodes field length prefixes, allowing MongoDB to skip over unneeded fields during query scans without parsing the entire.

3
Junior#Docker & Containers

What is an ObjectId (`_id`) and what are its 12 bytes composed of?

Every MongoDB document requires a unique primary key _id. By default, MongoDB generates a 12-byte ObjectId: 4 bytes: Unix epoch timestamp in seconds (provides natural chronological ordering) • 5 bytes: Random unique process identifier per machine/process • 3 bytes: Incrementing counter initialized to a random value.

4
Junior#Databases & SQL

What are the basic MongoDB CRUD operations?

Create: db.collection.insertOne({ .. • Read: db.collection.find({ status: "active" }) or findOne({ id.. • Update: db.collection.updateOne({ id.. • Delete: db.collection.deleteOne({ _id.

5
JuniorCode#mongodb#Basic

What is the difference between Embedding and Referencing documents?

The fundamental data modeling decision in MongoDB: Embedding (Denormalization - 1-to-few): Child data is stored directly inside the parent document as an array or object • Pros: Fetched in a single fast read operation without JOINs • Cons: Subject to 16 MB document size limit; can lead to data duplication.

6
Most AskedJunior#Databases & SQL

What is a Multikey Index in MongoDB?

When you index a field that contains an Array (e.g. tags: ["cloud", "k8s", "docker"]): MongoDB automatically creates a Multikey Index • It creates a separate index entry for every single element in the array • Queries like db.articles.find({ tags: "k8s" }) leverage the index directly.

7
Junior#mongodb#Basic

What is the difference between `$set`, `$unset`, `$push`, and `$pull` update operators?

Always use atomic update operators instead of replacing the entire document: set: Updates the value of a field, or creates it if it doesn't exist • unset: Deletes a specific field from a document • push: Appends a new element to an array • pull: Removes all matching elements from an array.

8
Junior#mongodb#Basic

What is the 16 MB Document Size Limit and how do you store larger files?

A single BSON document cannot exceed 16 Megabytes: Designed to prevent RAM bloat and preserve network transfer performance • For Larger Files (> 16 MB): Use GridFS.

9
Junior#Databases & SQL

What is a Capped Collection in MongoDB?

A Capped Collection is a fixed-size, circular collection that maintains insertion order: Once the allocated maximum size (e.g. 1 GB) is filled, new documents automatically overwrite the oldest documents in the collection (like a • Extremely fast for log ingestion, telemetry, and message buffering.

10
JuniorCode#Pipes#CI/CD & DevOps

What is the `$lookup` operator in the Aggregation Pipeline?

$lookup performs a left outer join between two collections in the same database.

Part 2: Core Architecture & Implementation (Mid-Level)

10 Questions
11
Most AskedSenior#System Design

How does the WiredTiger Storage Engine work internally?

WiredTiger is MongoDB's default pluggable storage engine since MongoDB 3.2: Concurrency: True document-level concurrency control (optimistic concurrency) • Compression: Transparent snappy or zlib compression on disk (cuts storage by 50-70%) • Cache Management: Allocates an internal WiredTiger Cache (typically 50% of (RAM - 1GB)).

12
SeniorCode#System Design#Databases & SQL

What is the MongoDB Journal and Checkpoints?

Journal (Write-Ahead Log): Sequential on-disk log recording all write operations before applying them to data files • Checkpoints: Every 60 seconds (or when journal exceeds 2 GB), WiredTiger takes a consistent snapshot of data in memory and flushes all dirty.

13
SeniorCode#Pipes#CI/CD & DevOps

How does the Aggregation Pipeline process data?

The Aggregation Pipeline is a multi-stage data processing framework modeled after Unix pipes (): Documents enter through the first stage; each stage transforms documents and passes output to the next stage • Key Stages • match: Filters documents (place at the beginning to utilize indexes!).

14
Most AskedSenior#System Design#Databases & SQL

What are Compound Indexes and Index Prefixes in MongoDB?

A compound index indexes multiple fields (e.g. { status: 1, createdAt: -1 }): Index Prefixes: Subsets of the index starting from the leftmost field • { status: 1 } is an index prefix (can be used by queries filtering on status) • { createdAt: -1 } is NOT a prefix and cannot be used alone!

15
Senior#System Design

What is Write Concern (`w`, `j`, `wtimeout`)?

Write Concern describes the level of acknowledgment requested from MongoDB for a write: w: 1 (Default): Acknowledges write as soon as the Primary node in memory commits the write • w: "majority": Acknowledges write only after a strict majority of replica set nodes have committed the write to their memory.

16
Senior#System Design

What is Read Concern (`local`, `available`, `majority`, `linearizable`)?

Controls the consistency and isolation of data returned by read operations: local (Default): Returns data from the node responding to the query without verifying if the data has been committed to a majority of nodes.

17
Senior#System Design#Databases & SQL

What is Read Preference in MongoDB Replica Sets?

Determines which replica set node receives read queries: primary (Default): All reads route to the Primary • primaryPreferred: Reads from Primary; falls back to Secondary if Primary is down • secondary: Reads strictly from Secondary nodes (offloads analytical reporting from primary; risk of reading stale data).

18
Senior#System Design#Databases & SQL

How does a MongoDB Replica Set elect a new Primary during failover?

A Replica Set uses a Raft-inspired election protocol: Nodes exchange heartbeats every 2 seconds • If Secondaries do not receive heartbeats from Primary for 10 seconds, an election is triggered • A Secondary nominates itself as candidate.

19
Senior#System Design#Databases & SQL

What is the Oplog (Operations Log) in MongoDB?

The oplog.rs is a special capped collection that records a rolling, chronological history of all data modification writes: Every insert, update, or delete on the Primary is converted into an idempotent operation and appended to the oplog • Secondary nodes tail the Primary's oplog and apply events to stay synchronized.

20
Most AskedSeniorCode#System Design#Databases & SQL

What is a TTL (Time-To-Live) Index in MongoDB?

A single-field index on a Date field that automatically deletes expired documents.

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

30 Questions
21
SeniorCode#System Design#Databases & SQL

What is the Sharding Architecture in MongoDB (mongos, Config Servers, Shards)?

MongoDB achieves horizontal scale-out by partitioning large collections across clusters: Shards: Each shard holds a subset of the sharded data • Config Servers: A dedicated 3-node replica set storing cluster metadata, shard boundaries, and routing mappings • mongos (Query Routers): Stateless routing proxies that applications connect to.

22
Senior#Databases & SQL

What makes a Good vs Bad Shard Key in MongoDB?

Selecting the right shard key is the most critical architectural decision: Bad Shard Key (Monotonically Increasing _id or timestamp) • All new writes route to the single shard owning the highest range • Creates a Hot Shard bottleneck while other shards sit idle • Bad Shard Key (Low Cardinality, e.g. country).

23
Senior#mongodb#Advanced Internals

What are Targeted Queries vs Scatter-Gather Queries in Sharded Clusters?

Targeted Query: The query includes the Shard Key in the find() criteria • Scatter-Gather Query: The query does NOT include the shard key.

24
Most AskedSeniorCode#State Management#Databases & SQL

How do Multi-Document ACID Transactions work in MongoDB?

Supported on Replica Sets (v4.0+) and Sharded Clusters (v4.2+): Provides full snapshot isolation across multiple collections and documents.

25
Senior#Microservices

What are Change Streams and how do they enable real-time reactive microservices?

Change Streams allow applications to subscribe to real-time data modifications without polling: Built directly on top of the oplog • Notifies applications instantly when documents are inserted, updated, replaced, or deleted • Resumable via Resume Tokens (_id of the change event) if the client connection drops.

26
Senior#Forms#Performance

How do you analyze query performance using `explain("executionStats")`?

Run db.collection.find(...).explain("executionStats"): executionStages.stage • IXSCAN: Good! • FETCH: Fetching full documents from disk based on index • COLLSCAN: Fatal Full Collection Scan!.

27
Senior#mongodb#Advanced Internals

What is the Working Set Size and how does it dictate RAM sizing?

The Working Set is the total volume of actively accessed data and indexes that must reside in RAM for optimal performance: If Working Set > RAM: WiredTiger is constantly forced to read pages from disk, causing massive disk I/O, cache page evictions, and severe.

28
Senior#System Design#Databases & SQL

What are Chunk Splits and the Balancer process in MongoDB Sharding?

Sharded data is divided into contiguous ranges called Chunks (default size: 64 MB): Chunk Split: When a chunk exceeds 64 MB, the primary shard splits it into two smaller chunks • The Balancer: A background thread running on the Config Server that monitors chunk distribution across shards.

29
Most AskedSeniorCode#Databases & SQL

What is a Partial Index vs a Sparse Index in MongoDB?

Sparse Index: Only indexes documents that contain the indexed field (skips documents where the field does not exist) • Partial Index (Modern Replacement): Indexes only documents that satisfy an explicit filter expression.

30
Senior#CLI#Security & Auth

What is Client-Side Field Level Encryption (CSFLE) in MongoDB?

Enterprise zero-trust encryption standard: Sensitive fields (e.g. Social Security Numbers, Credit Card numbers) are encrypted in memory on the client application driver using customer.

31
Senior#Databases & SQL

How do you handle schema versioning in MongoDB without downtime?

Use the Schema Versioning Pattern: Include a schemaVersion: 2 attribute on every document • In your application domain layer, write an adapter that accepts old versions and dynamically transforms them in memory to the modern structure • When an old document is updated, the app saves it with the newest schema version.

32
Most AskedSenior#Databases & SQL

What is an Arbiter in MongoDB and why is it discouraged in modern production?

An Arbiter is a lightweight replica set member that does not hold data and cannot become Primary: Its sole purpose is to provide a tie-breaking vote during elections to reach a quorum without paying for a full data replica.

33
Senior#mongodb#Advanced Internals

What is the difference between a Hidden and a Secondary node in a Replica Set?

Standard Secondary: Receives writes, votes in elections, and can be queried by clients using readPreference: "secondary" • Hidden Node (hidden: true, priority: 0): Copies oplog and holds full data, but is invisible to client applications and can never be elected Primary.

34
Most AskedSenior#System Design

What causes WiredTiger Cache Eviction stalls and how do you resolve them?

Occurs when write throughput or heavy reads cause dirty pages in the WiredTiger cache to exceed 20% of cache size: When dirty pages exceed thresholds, user application worker threads are forced to pause and write cache pages to disk themselves (client stalls).

35
Senior#Databases & SQL

When should you NOT use MongoDB?

Highly normalized schemas with complex relational multi-table JOINs: Relational databases (PostgreSQL/MySQL) are mathematically designed for • Strict column-store OLAP data warehousing: Analyzing billions of rows across a few columns is 100x faster in Snowflake or BigQuery.

36
Most AskedSenior#System Design

WiredTiger Storage Engine: Checkpointing, Cache, and Concurrency.

WiredTiger is MongoDB's default storage engine: Document-Level Concurrency: Uses optimistic concurrency control; multiple concurrent write operations can update different documents in the same • WiredTiger RAM Cache: Holds uncompressed documents in memory (defaults to 50\% \text{ RAM} - 1\text{GB}).

37
Senior#mongodb#Advanced Internals

Data Modeling: Embedding vs Referencing & The 16MB Document Limit.

Embedding (Denormalized): Stores sub-documents inside the parent document • Referencing (Normalized): Stores ObjectId foreign keys and joins using $lookup.

38
SeniorCode#Pipes#CI/CD & DevOps

Advanced Aggregation Pipeline: `$lookup`, `$unwind`, and `$facet`.

MongoDB Aggregation pipelines process documents through multi-stage data transforms: lookup: Performs a left outer join to another collection • unwind: Deconstructs an array field from input documents to output a document for each element.

39
Senior#System Design

Replica Set Architecture and Oplog Internals.

Oplog (Operations Log): A capped collection on the Primary storing an idempotent sequence of all write operations • Automated Failover: If the Primary stops sending heartbeats for 10 seconds, Secondaries hold an election using Raft consensus and elect the.

40
Senior#System Design

Write Concern vs Read Concern: Distributed Guarantees.

Write Concern (w) • w: 1: Primary confirms write in RAM (fastest, risk of data loss on failover) • w: 'majority': Write confirmed by a majority of replica set nodes • j: true: Confirmed written to on-disk journal file.

41
Senior#System Design#Databases & SQL

MongoDB Sharding Architecture: `mongos`, Config Servers, and Chunks.

Sharding distributes data horizontally across a cluster of Replica Sets: mongos (Query Router): Lightweight stateless proxy that routes client requests to the correct shard • Config Database: Replicated cluster storing cluster metadata and shard key routing ranges • Chunks: Data ranges of a collection (default 64MB).

42
Senior#mongodb#Advanced Internals

Shard Key Selection: Avoiding Hotspots.

The Shard Key determines which shard stores a document: Monotonically Increasing Keys (e.g. id or timestamp) (Anti-pattern): All new writes go exclusively to the highest shard chunk, creating a.

43
SeniorCode#System Design

Change Streams: Real-time Event-Driven Architectures.

Change Streams allow applications to subscribe to real-time data modifications at the collection, database, or deployment level without polling: Powered by tailing the replication Oplog • Emits insert, update, replace, and delete events directly into WebSockets, microservices, or Kafka topics.

44
Senior#Databases & SQL

Time-Series Collections in MongoDB 5.0+.

Designed for IoT telemetry, financial quotes, and system monitoring metrics: Declare with timeseries: { timeField: 'timestamp', metaField: 'metadata', granularity: 'minutes' } • Automatically organizes data into optimized columnar-like compressed disk buckets, reducing storage footprint by up to 70% compared to standard.

45
Most AskedSenior#State Management#Databases & SQL

Multi-Document ACID Transactions in MongoDB.

MongoDB 4.0+ supports multi-document ACID transactions across collections and replica sets (and across shards in 4.2+): Uses sessions (client.startSession()) • Commits via two-phase commit protocol (session.commitTransaction()).

46
Most AskedSenior#Databases & SQL

TTL (Time-To-Live) and Partial Indexes in MongoDB.

TTL Index: Automatically deletes documents after a specified number of seconds (expireAfterSeconds: 3600) • Partial Index: Indexes only documents matching a filter expression (partialFilterExpression: { active: true }), reducing index memory size.

47
Most AskedSenior#Databases & SQL

MongoDB Atlas Search & Vector Search (`knnVector`).

Atlas Search: Integrates Apache Lucene directly alongside MongoDB data, providing full-text search, fuzzy matching, and autocomplete with zero • Vector Search: Indexes high-dimensional vector embeddings with HNSW graphs for semantic AI searches, executing alongside standard MongoDB.

48
Senior#Forms

Schema Validation with JSON Schema (`$jsonSchema`).

Although MongoDB is schemaless, enterprise applications enforce data consistency using JSON Schema validation rules on collections: Enforces data types (bsonType: 'string'), required fields, minimum/maximum values, and regular expression patterns on INSERT and UPDATE operations.

49
Senior#Forms#Performance

Query Performance Tuning: `explain("executionStats")`.

COLLSCAN: Full collection scan (reading all documents) • IXSCAN: Index scan; only matching index keys are read • totalDocsExamined vs nReturned: In an optimal query, the ratio is 1:1.

50
Senior#mongodb#Advanced Internals

Enterprise Backup: `mongodump` vs Continuous Cloud Snapshots.

mongodump / mongorestore: Exports BSON data files • Continuous Cloud Snapshots (Atlas / EBS): Storage-level copy-on-write disk snapshots combined with continuous Oplog archiving, providing.