Top 50 MongoDB Interview Questions and Answers

Commonly asked MongoDB interview questions, from fundamentals to advanced concepts.

1.What is MongoDB?

MongoDB is a popular open-source NoSQL document database.

  • Stores data as flexible, JSON-like documents (BSON) instead of rows and tables.
  • Designed for scalability, high availability, and handling unstructured or rapidly evolving data.

2.What is the difference between SQL and MongoDB (relational vs document)?

They use fundamentally different data models:

  • SQL (relational): fixed schemas, data spread across normalized tables, joined via foreign keys.
  • MongoDB (document): flexible schemas, related data often embedded in a single document, reducing the need for joins.
  • MongoDB trades strict consistency/structure for schema flexibility and horizontal scalability.

3.What is a Document in MongoDB?

A Document is the basic unit of data in MongoDB — a JSON-like structure of key-value pairs, stored internally as BSON.

{ "_id": 1, "name": "Alice", "age": 30 }
  • Roughly analogous to a row in a relational database, but can have nested objects and arrays.

4.What is a Collection in MongoDB?

A Collection is a group of MongoDB documents, roughly analogous to a table in a relational database.

  • Unlike SQL tables, documents within the same collection don't need to share the same structure/schema.
  • Collections live inside a database.

5.What is BSON, and how does it differ from JSON?

BSON (Binary JSON) is the binary-encoded format MongoDB uses to store documents.

  • Adds support for extra data types not in standard JSON, like Date, ObjectId, and binary data.
  • More efficient to parse and traverse than text-based JSON, since it's designed for fast machine processing.

6.What is the _id field in MongoDB?

Every MongoDB document has a unique _id field acting as its primary key.

  • If not provided explicitly, MongoDB automatically generates a unique ObjectId.
  • Automatically indexed, ensuring fast lookups and uniqueness within a collection.

7.How do you insert a document into a MongoDB collection?

Use insertOne() or insertMany():

db.users.insertOne({ name: "Alice", age: 30 });
db.users.insertMany([{ name: "Bob" }, { name: "Carol" }]);
  • If _id isn't specified, MongoDB generates one automatically.

8.What is the difference between insertOne() and insertMany()?

Both add new documents, differing in quantity:

  • insertOne(): inserts a single document.
  • insertMany(): inserts an array of multiple documents in one call, more efficient than looping insertOne() calls individually.

9.How do you query documents in MongoDB using find()?

find() retrieves documents matching a filter.

db.users.find({ age: { $gt: 25 } });
db.users.find({ name: "Alice" }, { name: 1, age: 1 }); // projection
  • The first argument is the filter; the optional second is the projection (which fields to return).

10.What are Query Operators in MongoDB?

Query operators allow conditions beyond simple equality:

  • Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin.
  • Logical: $and, $or, $not, $nor.
  • Element: $exists, $type.
db.users.find({ age: { $gte: 18, $lte: 65 } });

11.What is the difference between updateOne(), updateMany(), and replaceOne()?

All modify existing documents, but differently:

  • updateOne(): modifies specific fields of the first matching document.
  • updateMany(): modifies specific fields of all matching documents.
  • replaceOne(): replaces the entire first matching document (except _id) with a new one.

12.What are Update Operators in MongoDB?

Update operators specify how fields should change:

  • $set: sets a field's value.
  • $inc: increments a numeric field.
  • $unset: removes a field.
  • $push: appends a value to an array field.
  • $pull: removes a value from an array field.
db.users.updateOne({ _id: 1 }, { $set: { age: 31 }, $inc: { loginCount: 1 } });

13.How do you delete documents in MongoDB?

Use deleteOne() or deleteMany():

db.users.deleteOne({ _id: 1 });
db.users.deleteMany({ active: false });
  • Both accept a filter specifying which documents to remove.

14.What is an Index in MongoDB, and why is it important?

An Index is a data structure that improves the speed of query operations on a collection.

db.users.createIndex({ email: 1 });
  • Without an index, MongoDB must perform a collection scan, checking every document — slow for large collections.
  • Comes with a write-performance trade-off, since indexes must be updated on every insert/update.

15.What are the different types of Indexes in MongoDB?

MongoDB supports several index types:

  • Single field: index on one field.
  • Compound: index on multiple fields together.
  • Multikey: automatically created when indexing an array field.
  • Text: supports text search across string fields.
  • Geospatial: supports location-based queries.

16.What is a Compound Index in MongoDB?

A Compound Index indexes multiple fields together in a single index structure.

db.orders.createIndex({ customerId: 1, orderDate: -1 });
  • Field order matters — the index supports queries filtering on a leftmost prefix of the indexed fields efficiently.

17.What is a Text Index in MongoDB?

A Text Index enables efficient full-text search across string fields.

db.articles.createIndex({ content: "text" });
db.articles.find({ $text: { $search: "mongodb tutorial" } });
  • A collection can have only one text index, though it can cover multiple fields.

18.What is the Aggregation Framework in MongoDB?

The Aggregation Framework processes documents through a multi-stage pipeline, transforming and summarizing data (similar to SQL's GROUP BY combined with multiple transformation steps).

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } }
]);

19.What are common stages in an aggregation pipeline?

Some frequently used pipeline stages:

  • $match: filters documents (like WHERE).
  • $group: groups documents and computes aggregates (like GROUP BY).
  • $project: reshapes documents, including/excluding/computing fields.
  • $sort: orders results.
  • $limit / $skip: pagination.
  • $lookup: performs a join with another collection.

20.What is the difference between $match and $group in an aggregation pipeline?

They serve different purposes in the pipeline:

  • $match: filters documents before further processing, similar to SQL's WHERE — reduces the dataset early for efficiency.
  • $group: groups the (already filtered) documents by a key and computes aggregate values per group, similar to GROUP BY.

21.What is Sharding in MongoDB?

Sharding distributes data across multiple servers (shards) to support horizontal scaling of very large datasets.

  • Each shard holds a subset of the data, determined by a shard key.
  • A mongos router process directs queries to the appropriate shard(s), making the distribution transparent to applications.

22.What is a Shard Key, and why is choosing it important?

A Shard Key is the field (or fields) MongoDB uses to distribute documents across shards.

  • A poorly chosen shard key can lead to uneven data distribution ("hotspotting"), where one shard receives disproportionate traffic.
  • A good shard key has high cardinality and distributes both storage and query load evenly.

23.What is Replication in MongoDB?

Replication maintains multiple copies of data across different servers for redundancy and availability.

  • Implemented via Replica Sets — a group of mongod instances maintaining the same data set.
  • Provides automatic failover: if the primary node goes down, a secondary is automatically elected as the new primary.

24.What is a Replica Set in MongoDB?

A Replica Set is a group of MongoDB servers that maintain the same data set, providing redundancy and high availability.

  • Consists of one Primary (handles all writes) and multiple Secondaries (replicate data from the primary, can serve reads).
  • If the primary fails, the remaining members automatically hold an election to choose a new primary.

25.What is the role of a Primary and Secondary node in a Replica Set?

They serve distinct roles within a Replica Set:

  • Primary: the only node that accepts write operations; all changes are recorded in its operation log (oplog).
  • Secondary: continuously replicates the primary's oplog to stay in sync, and can serve read queries (if read preference allows) or become primary during failover.

26.What happens during a Replica Set election?

An election occurs when the current primary becomes unavailable (crash, network partition, etc.).

  • Remaining eligible secondaries vote to elect a new primary, based on factors like data freshness and configured priority.
  • Once a new primary is elected, the replica set resumes accepting writes — this process typically takes just a few seconds.

27.What is the difference between embedding and referencing documents in MongoDB schema design?

Two main strategies for modeling relationships:

  • Embedding: nests related data directly inside the parent document — fast reads (single query), but can lead to large documents and duplicated data.
  • Referencing: stores an _id reference to a document in another collection (like a foreign key) — normalized, but requires an extra query or $lookup to join.

28.When would you choose embedding over referencing in MongoDB?

Embedding is generally preferred when:

  • The related data is always accessed together with the parent (e.g., an address embedded in a user document).
  • The nested data has a bounded size and doesn't grow unboundedly (avoiding the 16MB document size limit).
  • Referencing is better for data that's large, shared across many parents, or updated independently.

29.What are Transactions in MongoDB, and when were multi-document transactions introduced?

Multi-document ACID transactions were introduced in MongoDB 4.0 (for replica sets) and extended to sharded clusters in 4.2.

const session = client.startSession();
session.startTransaction();
// ... operations ...
await session.commitTransaction();
  • Before this, MongoDB only guaranteed atomicity at the single-document level.

30.What is the difference between MongoDB and a traditional RDBMS in terms of ACID guarantees?

Historically, they diverged significantly:

  • Traditional RDBMS: full ACID guarantees across multi-row, multi-table transactions by design.
  • MongoDB: originally guaranteed atomicity only at the single-document level; now supports full multi-document ACID transactions (since 4.0), though single-document operations remain the more idiomatic, higher-performance pattern.

31.What is Schema Validation in MongoDB?

Schema Validation lets you enforce rules on document structure within a collection, despite MongoDB's flexible schema.

db.createCollection("users", {
  validator: { $jsonSchema: { required: ["name", "email"] } }
});
  • Useful for catching malformed data early while still retaining schema flexibility where needed.

32.What is the mongoose library used for?

Mongoose is an Object Data Modeling (ODM) library for MongoDB in Node.js applications.

  • Provides schema definitions, validation, middleware (hooks), and a more structured way to interact with MongoDB from JavaScript/TypeScript.
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", userSchema);

33.What is the difference between findOne() and find()?

Both query documents, but return different results:

  • findOne(): returns a single document (the first match), or null if none found.
  • find(): returns a cursor over all matching documents, which must be iterated (or converted with .toArray()).

34.What is the purpose of the $lookup stage in aggregation?

$lookup performs a left outer join with another collection within an aggregation pipeline.

db.orders.aggregate([
  { $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customer"
  }}
]);
  • The most common way to combine data across collections in MongoDB, since it lacks traditional SQL joins.

35.What is a Capped Collection in MongoDB?

A Capped Collection is a fixed-size collection that automatically overwrites its oldest documents once it reaches its size limit.

  • Maintains insertion order and is ideal for use cases like logging or caching recent events, where old data can be safely discarded.
db.createCollection("logs", { capped: true, size: 100000 });

36.What is GridFS in MongoDB, and when is it used?

GridFS is a specification for storing and retrieving large files (bigger than the 16MB document size limit) in MongoDB.

  • Splits files into smaller chunks stored as separate documents, reassembled on retrieval.
  • Commonly used for storing images, videos, or other large binary files directly alongside other application data.

37.What is the difference between a Primary Key in SQL and the _id field in MongoDB?

Both uniquely identify a record, but differ slightly:

  • SQL Primary Key: developer-defined, can be a natural key or auto-incrementing integer.
  • MongoDB _id: automatically generated as a 12-byte ObjectId if not specified, encoding a timestamp, machine identifier, and counter — globally unique without coordination.

38.What is Write Concern in MongoDB?

Write Concern specifies the level of acknowledgment required from MongoDB before considering a write operation successful.

db.orders.insertOne(doc, { writeConcern: { w: "majority" } });
  • w: 1: acknowledged by the primary only.
  • w: "majority": acknowledged by a majority of replica set members — stronger durability guarantee at the cost of latency.

39.What is Read Concern in MongoDB?

Read Concern controls the consistency and isolation guarantees of data returned by a read operation.

  • "local": returns the most recent data, without guaranteeing it's been replicated.
  • "majority": returns data that has been acknowledged by a majority of replica set members, ensuring it won't be rolled back.

40.What is Read Preference in MongoDB?

Read Preference determines which replica set members a read operation can be routed to.

  • primary (default): reads always go to the primary.
  • secondary / secondaryPreferred: allows reads from secondaries, reducing load on the primary at the cost of potentially stale data.
  • nearest: routes to the replica with the lowest network latency.

41.What is the explain() method used for in MongoDB?

explain() shows how MongoDB plans to execute (or executed) a query, including whether an index was used.

db.users.find({ age: { $gt: 25 } }).explain("executionStats");
  • Essential for diagnosing slow queries and verifying indexes are being used effectively.

42.What is the difference between $set and $unset update operators?

Both modify a document's fields, oppositely:

  • $set: sets a field to a specified value (creating it if it doesn't exist).
  • $unset: removes a field from the document entirely.
db.users.updateOne({ _id: 1 }, { $unset: { tempFlag: "" } });

43.What is the upsert option in MongoDB update operations?

upsert: true tells an update operation to insert a new document if no document matches the filter, instead of doing nothing.

db.users.updateOne(
  { email: "a@x.com" },
  { $set: { lastLogin: new Date() } },
  { upsert: true }
);
  • Useful for "create or update" logic in a single atomic operation.

44.What is the purpose of the $exists operator?

$exists checks whether a field is present (or absent) in a document.

db.users.find({ phone: { $exists: true } });
db.users.find({ phone: { $exists: false } });
  • Useful when documents have varying schemas, since some may not have a given field at all.

45.What is Change Streams in MongoDB?

Change Streams let applications subscribe to real-time notifications of data changes (inserts, updates, deletes) in a collection.

const changeStream = db.orders.watch();
changeStream.on("change", (change) => console.log(change));
  • Built on the oplog, and requires a replica set (or sharded cluster) — useful for reactive applications and event-driven architectures.

46.What is the difference between a Standalone MongoDB deployment and a Replica Set?

They differ in redundancy and availability:

  • Standalone: a single mongod instance — no automatic failover, no built-in redundancy; a single point of failure.
  • Replica Set: multiple synchronized nodes providing automatic failover, redundancy, and (optionally) read scaling — the recommended setup for production.

47.What is Horizontal Scaling, and how does MongoDB achieve it?

Horizontal scaling ("scaling out") adds more servers to handle increased load, as opposed to vertical scaling (adding more power to a single server).

  • MongoDB achieves this through sharding, distributing data and query load across multiple shard servers.
  • Allows a MongoDB cluster to handle datasets and throughput far beyond what a single server could support.

48.What is the aggregation $project stage used for?

$project reshapes documents passing through the pipeline — including, excluding, renaming, or computing new fields.

db.users.aggregate([
  { $project: { name: 1, ageInMonths: { $multiply: ["$age", 12] } } }
]);
  • Similar in purpose to selecting specific columns (and computed expressions) in a SQL SELECT.

49.What is a MongoDB Cursor, and how do you iterate through it?

A Cursor is a pointer to the result set of a find() query — results aren't all loaded into memory at once.

const cursor = db.users.find();
while (await cursor.hasNext()) {
  console.log(await cursor.next());
}
  • Supports chaining methods like .sort(), .limit(), and .skip() before iteration begins.

50.What is the difference between NoSQL document stores like MongoDB and key-value stores like Redis?

Both are NoSQL, but optimized for different use cases:

  • MongoDB (document store): stores rich, structured/semi-structured documents, supports complex queries, indexing, and aggregation.
  • Redis (key-value store): extremely fast in-memory storage of simple key-value pairs (or basic structures like lists/sets), typically used for caching, session storage, or real-time counters rather than complex querying.