MongoDB Interview Questions and Answers | Tutorials Logic
Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials
MongoDB

Top 25 MongoDB Interview Questions

Curated questions covering documents, collections, CRUD, aggregation, indexing, replication, and sharding.

01

What is MongoDB?

MongoDB is a NoSQL document database that stores data as BSON (Binary JSON) documents. It is schema-flexible, horizontally scalable, and designed for high availability. Documents are stored in collections (analogous to tables in SQL).

02

What is the difference between SQL and MongoDB?

  • SQL — structured, table-based, fixed schema, ACID transactions, relational joins.
  • MongoDB — document-based, flexible schema, embedded documents instead of joins, horizontal scaling.
  • SQL: Table ? Row ? Column. MongoDB: Collection ? Document ? Field.
03

What is a document in MongoDB?

A document is a JSON-like record stored in BSON format. Documents can have nested objects and arrays. Each document has a unique _id field (ObjectId by default).

Example
{
  "_id": ObjectId("..."),
  "name": "Alice",
  "age": 25,
  "address": { "city": "NYC", "zip": "10001" },
  "tags": ["developer", "designer"]
}
04

What are the basic CRUD operations in MongoDB?

  • Create: insertOne(), insertMany()
  • Read: find(), findOne()
  • Update: updateOne(), updateMany(), replaceOne()
  • Delete: deleteOne(), deleteMany()
Example
db.users.insertOne({ name: "Alice", age: 25 });
db.users.find({ age: { $gt: 20 } });
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } });
db.users.deleteOne({ name: "Alice" });
05

What are MongoDB query operators?

  • Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
  • Logical: $and, $or, $not, $nor
  • Element: $exists, $type
  • Array: $all, $elemMatch, $size
  • Evaluation: $regex, $where
06

What is the aggregation pipeline in MongoDB?

The aggregation pipeline processes documents through a series of stages. Each stage transforms the data. Common stages: $match (filter), $group (aggregate), $project (reshape), $sort, $limit, $skip, $lookup (join), $unwind.

Example
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
]);
07

What are indexes in MongoDB?

Indexes improve query performance by allowing MongoDB to find documents without scanning the entire collection. Types: single field, compound, multikey (arrays), text, geospatial, hashed. The _id field is automatically indexed.

Example
db.users.createIndex({ email: 1 });           // ascending
db.users.createIndex({ name: 1, age: -1 });   // compound
db.users.createIndex({ email: 1 }, { unique: true }); // unique
08

What is the difference between embedded documents and references?

  • Embedded — store related data in the same document; faster reads; no joins needed; good for one-to-few relationships.
  • References — store ObjectId of related document; normalised; good for one-to-many or many-to-many; requires $lookup for joins.
09

What is $lookup in MongoDB?

$lookup performs a left outer join between two collections in the aggregation pipeline. It is MongoDB's equivalent of SQL JOIN.

Example
db.orders.aggregate([
  { $lookup: {
    from: "users",
    localField: "userId",
    foreignField: "_id",
    as: "user"
  }}
]);
10

What is replication in MongoDB?

Replication provides high availability through replica sets — a group of MongoDB instances that maintain the same data. One primary node accepts writes; secondary nodes replicate data. If the primary fails, an election promotes a secondary.

11

What is sharding in MongoDB?

Sharding distributes data across multiple machines (shards) for horizontal scaling. A shard key determines how data is distributed. Components: shards (data), mongos (router), config servers (metadata).

12

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

find() returns a cursor to all matching documents. findOne() returns the first matching document directly (or null). Use findOne() when you expect a single result.

13

What are update operators in MongoDB?

  • $set — set field value
  • $unset — remove a field
  • $inc — increment a numeric field
  • $push — add to array
  • $pull — remove from array
  • $addToSet — add to array if not present
Example
db.users.updateOne(
  { _id: id },
  { $set: { name: "Bob" }, $inc: { loginCount: 1 }, $push: { tags: "admin" } }
);
14

What is the ObjectId in MongoDB?

ObjectId is the default _id type — a 12-byte BSON type consisting of: 4-byte timestamp, 5-byte random value, 3-byte incrementing counter. It is unique across machines and encodes creation time.

15

What is the difference between $push and $addToSet?

$push adds an element to an array even if it already exists (allows duplicates). $addToSet adds an element only if it is not already present (maintains uniqueness).

16

What is a capped collection?

A capped collection is a fixed-size collection that automatically overwrites the oldest documents when it reaches its size limit. Useful for logs and caches. Documents are stored in insertion order.

17

What is the explain() method?

explain() returns information about how MongoDB executes a query — including whether an index was used, number of documents scanned, and execution time. Essential for query optimisation.

Example
db.users.find({ age: { $gt: 25 } }).explain("executionStats");
18

What is the difference between $match and $filter?

$match is an aggregation pipeline stage that filters documents (like WHERE in SQL). $filter is an aggregation operator that filters elements within an array field.

19

What are transactions in MongoDB?

MongoDB 4.0+ supports multi-document ACID transactions across replica sets. MongoDB 4.2+ supports transactions across sharded clusters. Use sessions to group operations into a transaction.

Example
const session = client.startSession();
session.startTransaction();
try {
  await col1.insertOne({ ... }, { session });
  await col2.updateOne({ ... }, { ... }, { session });
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
}
20

What is the difference between MongoDB and Redis?

  • MongoDB — document database; persistent storage; complex queries; good for primary data store.
  • Redis — in-memory key-value store; extremely fast; used for caching, sessions, pub/sub, and leaderboards.
  • They are often used together: MongoDB for persistence, Redis for caching.
21

What is the $unwind stage?

$unwind deconstructs an array field, outputting one document per array element. Used before grouping or processing array elements individually.

Example
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: "$items.product", total: { $sum: "$items.qty" } } }
]);
22

What is a text index in MongoDB?

A text index supports full-text search on string fields. Only one text index per collection. Use $text operator to search.

Example
db.articles.createIndex({ title: "text", body: "text" });
db.articles.find({ $text: { $search: "mongodb tutorial" } });
23

What is the difference between save() and insert()?

insert() always creates a new document. save() (deprecated in newer drivers) inserts if no _id is present, or replaces the document if _id exists. Use insertOne()/replaceOne() instead.

24

What is the mongodump and mongorestore?

mongodump exports a MongoDB database to BSON files. mongorestore imports those files back. Used for backups and migrations. For large databases, consider MongoDB Atlas backup or oplog-based solutions.

25

What is the difference between $project and $addFields?

  • $project — reshapes documents; can include, exclude, or rename fields; excluded fields are removed.
  • $addFields — adds new fields to documents without removing existing ones.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.