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

MongoDB Interview Questions

MongoDB

Top 25 MongoDB Interview Questions

Curated questions covering CRUD, aggregation pipeline, indexes, schema design, Mongoose, and MongoDB Atlas.

01

What is MongoDB and how does it differ from a relational database?

  • MongoDB is a NoSQL document database that stores data as BSON (Binary JSON) documents in collections.
  • Relational DB — structured tables with fixed schema, rows, and SQL queries; enforces relationships via foreign keys.
  • MongoDB — flexible schema, nested documents, no joins required; scales horizontally; better for hierarchical/unstructured data.
02

What is BSON in MongoDB?

BSON (Binary JSON) is the binary-encoded serialisation format MongoDB uses to store documents. It extends JSON with additional data types like Date, ObjectId, Binary, and Int32/Int64, and is more efficient to parse than plain JSON.

03

What are collections and documents in MongoDB?

A collection is a group of MongoDB documents, analogous to a table in a relational database. A document is a BSON record (key-value pairs), analogous to a row. Documents in the same collection can have different fields (flexible schema).

04

What are the basic CRUD operations in MongoDB?

  • Create: insertOne(), insertMany()
  • Read: find(), findOne()
  • Update: updateOne(), updateMany(), replaceOne()
  • Delete: deleteOne(), deleteMany()
Example
// Insert
db.users.insertOne({ name: "Alice", age: 25 });

// Read
db.users.find({ age: { $gt: 20 } });

// Update
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } });

// Delete
db.users.deleteOne({ name: "Alice" });
05

What are common query operators in MongoDB?

  • $eq / $ne — equal / not equal
  • $gt / $gte / $lt / $lte — comparison operators
  • $in / $nin — value in / not in array
  • $and / $or / $not / $nor — logical operators
  • $exists — field existence check
  • $regex — pattern matching
Example
db.products.find({
  price: { $gte: 10, $lte: 100 },
  category: { $in: ["electronics", "books"] },
  $or: [{ stock: { $gt: 0 } }, { preorder: true }]
});
06

What is projection in MongoDB?

Projection controls which fields are returned in query results. Pass a second argument to find() with 1 to include or 0 to exclude fields. You cannot mix inclusions and exclusions (except for _id).

Example
// Return only name and email, exclude _id
db.users.find({}, { name: 1, email: 1, _id: 0 });
07

What is the aggregation pipeline in MongoDB?

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

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

What is $lookup in MongoDB aggregation?

$lookup performs a left outer join between two collections, similar to SQL JOIN. It adds an array of matching documents from the joined collection.

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

What are indexes in MongoDB and why are they important?

Indexes improve query performance by allowing MongoDB to find documents without scanning the entire collection. Without an index, MongoDB performs a full collection scan (COLLSCAN). Common index types: single field, compound, text, geospatial, hashed.

Example
// Single field index
db.users.createIndex({ email: 1 });

// Compound index
db.orders.createIndex({ userId: 1, createdAt: -1 });

// Text index
db.articles.createIndex({ title: "text", body: "text" });
10

What is the explain() method in MongoDB?

explain() returns information about how MongoDB executes a query — whether it uses an index (IXSCAN) or a full scan (COLLSCAN), the number of documents examined, and execution time. Use it to diagnose slow queries.

Example
db.users.find({ email: "alice@example.com" }).explain("executionStats");
11

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

  • Embedding — store related data in the same document. Best for one-to-few relationships and data accessed together.
  • Referencing — store the ObjectId of a related document. Best for one-to-many or many-to-many relationships and large sub-documents.
  • Rule of thumb: embed for read performance; reference for write performance and data that changes independently.
12

What is ObjectId in MongoDB?

ObjectId is the default type for the _id field. It is a 12-byte BSON type: 4 bytes timestamp, 5 bytes random value, 3 bytes incrementing counter. It is unique across machines and sortable by creation time.

13

Does MongoDB support transactions?

Yes. MongoDB 4.0+ supports multi-document ACID transactions within a replica set. MongoDB 4.2+ supports transactions across sharded clusters. Transactions use sessions and follow the same commit/abort pattern as relational databases.

Example
const session = client.startSession();
session.startTransaction();
try {
  await accounts.updateOne({ _id: fromId }, { $inc: { balance: -100 } }, { session });
  await accounts.updateOne({ _id: toId },   { $inc: { balance:  100 } }, { session });
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
}
14

What is a replica set in MongoDB?

A replica set is a group of MongoDB instances that maintain the same data. It consists of one primary (accepts writes) and one or more secondaries (replicate data). If the primary fails, an election promotes a secondary, providing high availability.

15

What is sharding in MongoDB?

Sharding is MongoDB's horizontal scaling mechanism. Data is distributed across multiple shards (servers) based on a shard key. A mongos router directs queries to the appropriate shard(s). It enables handling datasets larger than a single server's capacity.

16

What is Mongoose and what does it provide?

Mongoose is an ODM (Object Document Mapper) for MongoDB and Node.js. It provides schema definition, validation, middleware (hooks), virtuals, and a query builder on top of the native MongoDB driver.

Example
const userSchema = new mongoose.Schema({
  name:  { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age:   { type: Number, min: 0 }
});
const User = mongoose.model("User", userSchema);
const user = await User.create({ name: "Alice", email: "a@b.com", age: 25 });
17

What is populate() in Mongoose?

populate() replaces a referenced ObjectId with the actual document from the referenced collection, similar to a JOIN. It is Mongoose-specific and works with ref fields.

Example
const postSchema = new mongoose.Schema({
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: "User" }
});
const post = await Post.findById(id).populate("author", "name email");
console.log(post.author.name); // "Alice"
18

What is lean() in Mongoose?

lean() returns plain JavaScript objects instead of full Mongoose documents. This skips hydration (no getters, virtuals, or methods), making queries significantly faster and using less memory — ideal for read-only operations.

Example
const users = await User.find({ active: true }).lean();
// users is a plain array of JS objects, not Mongoose Documents
19

What is GridFS in MongoDB?

GridFS is a specification for storing and retrieving files larger than the 16MB BSON document size limit. It splits files into chunks (default 255KB) stored in two collections: fs.files (metadata) and fs.chunks (binary data).

20

What are capped collections in MongoDB?

Capped collections are fixed-size collections that automatically overwrite the oldest documents when the size limit is reached. They maintain insertion order and are useful for logs, caches, and event streams.

Example
db.createCollection("logs", {
  capped: true,
  size: 1048576, // 1MB
  max: 1000      // max 1000 documents
});
21

What are TTL indexes in MongoDB?

TTL (Time To Live) indexes automatically delete documents after a specified number of seconds. They are useful for session data, temporary tokens, and log entries.

Example
// Documents expire 1 hour after createdAt
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }
);
22

What is MongoDB Atlas?

MongoDB Atlas is the fully managed cloud database service for MongoDB. It provides automated backups, scaling, monitoring, global clusters, Atlas Search (full-text search), Atlas Data API, and integrations with AWS, GCP, and Azure.

23

What is the $unwind stage in aggregation?

$unwind deconstructs an array field, outputting one document per array element. It is used before grouping or filtering on array contents.

Example
// Each tag becomes a separate document
db.articles.aggregate([
  { $unwind: "$tags" },
  { $group: { _id: "$tags", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
]);
24

What update operators are available in MongoDB?

  • $set — sets the value of a field.
  • $unset — removes a field.
  • $inc — increments a numeric field.
  • $push / $pull — add/remove elements from an array.
  • $addToSet — adds to array only if not already present.
  • $rename — renames a field.
Example
db.users.updateOne(
  { _id: userId },
  {
    $set:  { lastLogin: new Date() },
    $inc:  { loginCount: 1 },
    $push: { tags: "premium" }
  }
);
25

How do you perform text search in MongoDB?

Create a text index on one or more string fields, then use the $text query operator with $search. MongoDB tokenises and stems the search terms.

Example
db.articles.createIndex({ title: "text", body: "text" });

db.articles.find(
  { $text: { $search: "mongodb aggregation" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });

Ready to Level Up Your Skills?

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