70 Topics
Chapter•360 Minutes

70 Progressive Questions (Easy to Advanced + Scenarios)

70 comprehensive interview questions spanning database basics, Mongoose ODM abstractions, advanced aggregation pipelines, system architecture, performance tuning, and real-world scenario challenges.

Q1: What is MongoDB and how does it differ from traditional RDBMS?

MongoDB is a source-available, document-oriented NoSQL database that stores data as flexible BSON (Binary JSON) documents. Unlike traditional RDBMS (which uses structured tables, fixed schemas, and SQL joins), MongoDB provides flexible dynamic schemas, high availability via replica sets, and native horizontal scaling through sharding.

Key Takeaways
  • Dynamic dynamic schemas vs. fixed relational tables.

  • Stores data in BSON format with native nested objects and arrays.

Knowledge Check

Which data format does MongoDB use internally to store and query documents?

Q2: What is Mongoose and why use it over the native MongoDB driver?

Mongoose is an Object Data Modeling (ODM) library for Node.js. While the native driver provides direct low-level CRUD access, Mongoose adds structure by providing schema validation, type casting, middleware hooks (pre/post), dynamic virtuals, and populated document references.

Key Takeaways
  • Mongoose provides an ODM layer with schema enforcement.

  • Includes auto-casting, middleware hooks, populate references, and validation.

Knowledge Check

What is the primary role of Mongoose in a Node.js application?

Q3: What is BSON and how does it extend standard JSON?

BSON stands for Binary JSON. It is a binary-encoded serialization format used by MongoDB to store data and execute operations. BSON extends JSON by adding support for extra data types (e.g., ObjectId, Date, BinData, Decimal128, Long) and enables faster traversal and indexing by prefixing fields with byte lengths.

Key Takeaways
  • Extends JSON with native types like Date, ObjectId, and 64-bit Int.

  • Includes length prefixes for fast traversal.

Knowledge Check

Which of the following data types is supported natively in BSON but NOT in standard JSON?

Q4: Explain the structure of a MongoDB ObjectId.

An ObjectId is a 12-byte BSON value designed to guarantee uniqueness across distributed systems without a central authority:

  • 4 bytes: Timestamp value (seconds since epoch).
  • 5 bytes: Random value unique to the machine and process.
  • 3 bytes: Incrementing counter initialized to a random value.
Key Takeaways
  • Total size: 12 bytes.

  • First 4 bytes encode a UTC timestamp, allowing natural sorting by creation time.

Knowledge Check

How many bytes does a standard MongoDB ObjectId consume?

Q5: What is the difference between a Mongoose Schema and a Mongoose Model?

A Schema defines the structure, default values, validators, and middleware hooks for documents within a collection. A Model is a compiled constructor built from a Schema that provides the concrete interface to perform database CRUD operations (User.find(), User.create()).

Schema Definition vs Model Creation
const mongoose = require('mongoose');

// 1. Define Schema (Blueprint)
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, unique: true }
});

// 2. Compile Model (Database Interface)
const User = mongoose.model('User', userSchema);

The Schema defines attributes and rules; the Model compiles the schema into an executable database interface.

Key Takeaways
  • Schema = Blueprint & Rules.

  • Model = Compiled class providing CRUD access methods.

Knowledge Check

Which Mongoose call creates the database query interface from a defined schema?

Q6: When should you embed documents vs reference them in MongoDB?

  • Embed (Denormalization): Use when data has a 1-to-1 or 1-to-Few relationship, is accessed together frequently, and data doesn't grow unbounded (e.g., user address list).
  • Reference (Normalization): Use when data has a 1-to-Many (unbounded) or Many-to-Many relationship, data is updated independently, or document size approaches the 16MB limit.
Key Takeaways
  • Embed for atomic updates and high-speed read joins.

  • Reference for large, unbounded collections or shared entities.

Knowledge Check

Which pattern is recommended for storing a blog post's tags (5 to 10 tags per post)?

Q7: What is the maximum document size limit in MongoDB, and how do you store larger files?

The maximum BSON document size limit is 16 Megabytes. This prevents individual documents from overloading RAM or network bandwidth during retrieval. To store files or documents exceeding 16MB, MongoDB provides GridFS, which splits files into 255KB chunks across two collections (fs.files and fs.chunks).

Key Takeaways
  • 16MB maximum single BSON document limit.

  • Use GridFS to automatically chunk and stream large files.

Knowledge Check

Which built-in MongoDB feature supports storing single files exceeding 16MB?

Q8: What are the basic CRUD operations in Mongoose?

  • Create: Model.create({ name: 'Alice' }) or const doc = new Model(); await doc.save();
  • Read: Model.find({ age: { $gte: 18 } }), Model.findOne(), Model.findById()
  • Update: Model.updateOne({ _id }, { $set: { status: 'active' } }), Model.findByIdAndUpdate()
  • Delete: Model.deleteOne({ _id }), Model.findByIdAndDelete()
Key Takeaways
  • save() triggers validation and pre/post save hooks.

  • updateOne/updateMany bypass document instance hooks unless explicitly configured.

Knowledge Check

Which method instantiates a document and triggers Mongoose pre-save middleware hooks?

Q9: Explain fundamental comparison operators in MongoDB ($eq, $gt, $in, $nin).

Comparison operators match field values against criteria:

  • $gt / $gte: Greater than / Greater than or equal to.
  • $lt / $lte: Less than / Less than or equal to.
  • $in: Matches any value specified in an array status: { $in: ['active', 'pending'] }.
  • $nin: Matches values not present in the specified array.
Key Takeaways
  • $in evaluates array matches in a single query pass.

  • Combine operators for bounded range searches { age: { $gte: 18, $lte: 65 } }.

Knowledge Check

Which operator finds documents where a status field equals EITHER 'active' OR 'verified'?

Q10: How do logical query operators ($and, $or, $nor, $not) work?

Logical operators join multiple clause conditions:

  • $or: Returns documents matching at least one clause: { $or: [{ role: 'admin' }, { points: { $gt: 100 } }] }.
  • $and: Joins conditions implicitly or explicitly when querying the same field multiple times.
  • $nor: Returns documents failing all listed conditions.
Key Takeaways
  • Implicit $and occurs when comma-separating conditions in a query object.

  • Use explicit $and when targeting the same operator key multiple times.

Knowledge Check

When is an explicit $and operator required in a MongoDB query?

Q11: How does built-in and custom schema validation work in Mongoose?

Mongoose validates documents against schema constraints prior to saving:

  • Built-in: required, min, max, enum, minLength, match (regex).
  • Custom Validator: Defined using the validate key taking a validator function or regex alongside a custom error message string.
Custom Mongoose Schema Validator
const userSchema = new mongoose.Schema({
  phone: {
    type: String,
    validate: {
      validator: function(v) {
        return /\d{3}-\d{3}-\d{4}/.test(v);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
    required: [true, 'User phone number required']
  }
});

Validates input phone strings against regex patterns before writing to the database.

Key Takeaways
  • Validation runs automatically on doc.save().

  • Can enable validation on updates via { runValidators: true } option.

Knowledge Check

Does Model.findByIdAndUpdate() trigger schema validators by default in Mongoose?

Q12: What are Mongoose Virtuals and how do getters and setters work?

Virtuals are document properties that are not persisted to MongoDB database storage. They are computed dynamically at runtime (e.g., combining firstName and lastName into fullName). Getters compute output values, while Setters parse assigned values back into underlying document fields.

Key Takeaways
  • Virtuals consume zero database storage.

  • Enable toJSON: { virtuals: true } options to include virtuals in API JSON payloads.

Knowledge Check

Are Mongoose Virtual attributes stored directly inside MongoDB collection documents?

Q13: What are Mongoose Pre and Post Middleware hooks?

Middleware (also called hooks) are functions passed execution control during document operations.

  • Pre Hooks: Run before an event executes (e.g., hashing password before pre('save')).
  • Post Hooks: Run after an event completes (e.g., sending welcome emails after post('save')).
Pre-Save Password Hashing Middleware
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 10);
});

Intercepts document save events to hash passwords conditionally before writing.

Key Takeaways
  • Supported hook types: Document, Query, Aggregate, Model.

  • Commonly used for password hashing, auditing, and cascading cleanups.

Knowledge Check

Inside a document pre('save') middleware function, what does 'this' refer to?

Q14: What are Indexes in MongoDB, and why are they crucial for performance?

Indexes are specialized B-Tree data structures that store a small portion of the collection dataset in an easily traversable order. Without indexes, MongoDB performs a Collection Scan (COLLSCAN), inspecting every document. With indexes, MongoDB performs an Index Scan (IXSCAN), retrieving matching documents instantly.

Key Takeaways
  • Reduces query time complexity from $O(N)$ to $O(log N)$.

  • Trade-off: Speeds up reads but adds memory overhead and slightly slows writes.

Knowledge Check

Which scan type occurs when a query executes without an applicable index?

Q15: What is the difference between a Single-Field Index and a Compound Index?

  • Single-Field Index: Index constructed on a single key { email: 1 }.
  • Compound Index: Index constructed on multiple keys { status: 1, createdAt: -1 }. The order of fields matters significantly; queries must follow the Equality, Sort, Range (ESR) rule and match index prefix sequences.
Key Takeaways
  • Compound indexes support queries on prefix subsets of fields.

  • Follow the ESR Rule: Equality fields first, Sort fields second, Range fields last.

Knowledge Check

Given a compound index { a: 1, b: 1, c: 1 }, which query CANNOT utilize this index efficiently?

Q16: Explain the ESR (Equality, Sort, Range) Rule for compound indexes.

The ESR Rule guides optimal compound index field placement:

  1. E (Equality): Put fields matched on exact values first (status: 'active').
  2. S (Sort): Put fields used for ordering second (createdAt: -1).
  3. R (Range): Put fields filtered by inequality ranges last (age: { $gt: 21 }).
Key Takeaways
  • Equality fields $ o$ Sort fields $ o$ Range fields.

  • Prevents in-memory sorting operations (SORT stage in explain execution).

Knowledge Check

Applying the ESR rule to find({ status: 'A', age: { $gt: 20 } }).sort({ name: 1 }), what is the optimal compound index order?

Q17: What are Unique, Sparse, and Partial Indexes?

  • Unique Index: Rejects duplicate values for indexed fields.
  • Sparse Index: Only indexes documents that actually contain the indexed field (ignores documents missing the key).
  • Partial Index: Indexes documents satisfying a specified filter expression (partialFilterExpression), reducing index memory footprint.
Key Takeaways
  • Unique indexes enforce database-level uniqueness.

  • Partial indexes save RAM by indexing specific document subsets.

Knowledge Check

Which index type allows unique constraints on optional fields without throwing errors on multiple missing null entries?

Q18: What is a Time-To-Live (TTL) Index and how is it used?

A TTL index is a single-field index on a Date field that automatically removes documents from a collection after a specified duration (in seconds). A background thread wakes up every 60 seconds to purge expired documents. Ideal for sessions, verification OTPs, and temporary logs.

Creating a TTL Index in Mongoose
const sessionSchema = new mongoose.Schema({
  userId: String,
  createdAt: { 
    type: Date, 
    default: Date.now, 
    expires: 3600 // Automatically deletes document after 1 hour (3600s)
  }
});

Configures automatic document deletion 3600 seconds after creation time.

Key Takeaways
  • Automatically purges documents based on date fields.

  • Must be created on single date-type fields.

Knowledge Check

How often does the MongoDB background thread run to delete expired TTL index documents?

Q19: What is a Multikey Index?

When an index is created on a field that contains an array value, MongoDB automatically creates a Multikey Index. It indexes each individual element inside the array separately. Limitations: A compound index can index at most ONE array field.

Key Takeaways
  • Automatically created when indexing array fields.

  • Cannot construct compound multikey indexes spanning multiple array fields.

Knowledge Check

Can a compound index include two separate array fields in MongoDB?

Q20: How do Text Indexes and Geospatial Indexes operate?

  • Text Index: Supports searching string content for keywords, stemming, and relevance scoring ($text: { $search: 'database' }).
  • 2dsphere Index: Supports queries on a two-dimensional sphere (Earth geometry) using GeoJSON objects (Point, Polygon) for proximity queries like $near and $geoWithin.
Key Takeaways
  • Text indexes enable full-text search and keyword relevance ranking.

  • 2dsphere indexes calculate physical spherical distances using GeoJSON.

Knowledge Check

Which GeoJSON type is used to represent location coordinates [longitude, latitude] for 2dsphere queries?

Q21: What is the MongoDB Aggregation Framework and how does it work?

The Aggregation Framework is a data processing pipeline model. Documents enter a multi-stage pipeline that transforms, filters, groups, sorts, and reshapes them into aggregated results. Each stage passes its calculated output directly to the next stage.

Key Takeaways
  • Multi-stage transformation pipeline.

  • Executes native database analytics bypassing application memory processing.

Knowledge Check

How do aggregation stages pass data forward down the pipeline?

Q22: Explain $match, $group, and $project pipeline stages.

  • $match: Filters documents to allow only those matching specified conditions to pass (place $match first to leverage indexes).
  • $group: Groups input documents by a specified _id expression and applies accumulator operators ($sum, $avg, $push).
  • $project: Reshapes documents by adding, removing, or renaming fields.
Basic Aggregation Pipeline Example
db.orders.aggregate([
  { $match: { status: 'completed' } }, // 1. Filter
  { $group: {
      _id: '$customerId', 
      totalSpent: { $sum: '$amount' }, // 2. Group & Sum
      orderCount: { $sum: 1 }
  }},
  { $sort: { totalSpent: -1 } } // 3. Sort
]);

Filters completed orders, groups by customer ID, calculates total expenditure, and orders results.

Key Takeaways
  • Place $match as early as possible to reduce document volume.

  • $group performs SQL GROUP BY aggregations.

Knowledge Check

Why should $match stages be placed at the very beginning of an aggregation pipeline?

Q23: How does the $lookup stage perform left outer joins between collections?

The $lookup stage performs a left outer join to pull documents from another collection into an array field:

  • from: Target collection name.
  • localField: Key field in current collection.
  • foreignField: Key field in target collection.
  • as: Output array field name.
Key Takeaways
  • Performs left outer joins between collections.

  • Outputs matching joined documents into an array field.

Knowledge Check

What data type does the $lookup stage produce for the joined output 'as' field?

Q24: What does the $unwind stage do in an aggregation pipeline?

The $unwind stage deconstructs an array field from input documents to output a document for each element of the array. Each output document replaces the array with an individual element item. Commonly paired with $lookup to flatten joined arrays.

Key Takeaways
  • Deconstructs array fields into individual document streams.

  • Use preserveNullAndEmptyArrays: true to keep documents missing the array.

Knowledge Check

If a document contains an array of 3 items, how many output documents will $unwind produce for that document?

Q25: What are $facet and $bucket stages used for?

  • $facet: Executes multiple aggregation sub-pipelines concurrently within a single stage on the same input documents (useful for multi-faceted search and dashboard filtering).
  • $bucket: Categorizes incoming documents into groups (buckets) based on specified boundaries and criteria.
Key Takeaways
  • $facet powers multi-faceted search breakdowns in a single query.

  • $bucket categorizes numbers into defined numerical range groups.

Knowledge Check

Which stage allows running parallel aggregation pipelines to compute search results and category totals in one query pass?

Q26: What is the purpose of $addFields (or $set) in aggregation?

The $addFields stage adds new computed fields or modifies existing fields in passing documents without removing un-mentioned existing fields (unlike $project, which excludes un-specified fields unless explicitly preserved).

Key Takeaways
  • Adds or overrides specific document fields.

  • Preserves all existing document keys automatically.

Knowledge Check

How does $addFields differ from $project in aggregation?

Q27: What is the RAM limit for an aggregation stage, and how do you bypass it?

Pipeline stages have a default memory limit of 100 Megabytes of RAM. If a stage (like $sort or $group) exceeds 100MB, MongoDB throws an error. To bypass this, pass { allowDiskUse: true }, allowing pipeline stages to spill temporary data to disk files.

Key Takeaways
  • Default aggregation stage RAM ceiling: 100MB.

  • Use { allowDiskUse: true } to write intermediate data to temporary disk space.

Knowledge Check

Which query option allows aggregation stages to exceed the 100MB RAM processing limit?

Q28: How does Mongoose .populate() work, and what are its performance trade-offs?

populate() automates replacing specified document path references (ObjectId) with actual documents from another collection. Trade-off: Under the hood, populate() executes separate additional queries in application code (not a native database engine join), which can lead to $N+1$ query performance issues if misused.

Mongoose Populate Usage
const post = await Post.findById(postId)
  .populate('author', 'name email') // Replace author ObjectId with name and email
  .exec();

Retrieves post documents and executes a secondary query to fetch matching author details.

Key Takeaways
  • Fills referenced ObjectIds with full document objects.

  • Executes secondary queries under the hood; use $lookup for complex native joins.

Knowledge Check

Does Mongoose .populate() execute a native database join inside MongoDB engine memory?

Q29: What is the .lean() method in Mongoose, and why does it boost read performance?

By default, Mongoose query results return heavy Mongoose Document instances complete with internal state, getters/setters, change tracking, and method bindings. Chaining .lean() tells Mongoose to skip document hydration and return plain JavaScript objects (POJOs), making reads up to 5x faster.

Key Takeaways
  • Returns plain JavaScript objects instead of heavy Mongoose Document instances.

  • Drastically reduces CPU and memory overhead for read-heavy APIs.

Knowledge Check

What capability do you lose when executing a query with .lean() in Mongoose?

Q30: Does MongoDB support ACID Transactions? How do multi-document transactions work?

Yes, MongoDB supports full multi-document ACID transactions (starting in version 4.0 for Replica Sets and 4.2 for Sharded Clusters). Transactions allow executing multiple read/write operations atomically using a session (session.startTransaction()). If an operation fails, calling abortTransaction() rolls back all updates.

Mongoose Multi-Document Transaction
const session = await mongoose.startSession();
session.startTransaction();
try {
  await Account.updateOne({ _id: fromId }, { $inc: { balance: -100 } }, { session });
  await Account.updateOne({ _id: toId }, { $inc: { balance: 100 } }, { session });
  await session.commitTransaction();
} catch (err) {
  await session.abortTransaction();
} finally {
  session.endSession();
}

Executes account balance updates inside a session transaction, committing or aborting atomically.

Key Takeaways
  • Multi-document ACID transactions require Replica Sets or Sharded Clusters.

  • Managed via Client Sessions (session.commitTransaction()).

Knowledge Check

Which deployment architecture is required to run multi-document ACID transactions in MongoDB?