Top 15 MongoDB Interview Questions
Boost your MongoDB interview preparation with 15 crucial questions and answers, covering fundamental to advanced concepts.
1. What is MongoDB, and why is it used?
Answer: MongoDB is a NoSQL database that stores data in a flexible, JSON-like format called BSON. It is used because it is highly scalable, supports high performance, and allows for schema-less design, making it suitable for handling large volumes of unstructured or semi-structured data.
2. Explain the difference between MongoDB and RDBMS.
Answer:
Feature | MongoDB (NoSQL) | RDBMS |
Data Storage | BSON (Binary JSON) documents | Tables with rows and columns |
Schema | Schema-less | Schema-based |
Scalability | Horizontally scalable | Vertically scalable |
Transactions | Limited ACID transactions | Full ACID transactions |
MongoDB is better for large-scale, dynamic applications, whereas RDBMS is preferred for structured, transactional data.
3. What is a replica set in MongoDB?
Answer: A replica set is a group of MongoDB servers that maintain the same data set, providing redundancy and high availability. It consists of:
Primary Node: Accepts write operations.
Secondary Nodes: Replicate data from the primary.
Arbiter: Helps in election processes but doesnโt store data.
4. How does MongoDB handle indexing?
Answer: MongoDB uses B-tree indexing. You can create indexes on fields to improve query performance. Common types of indexes in MongoDB are:
Single Field Index: Index on one field.
Compound Index: Index on multiple fields.
Text Index: Index for text search.
2dsphere Index: Index for geospatial queries.
Example:
db.collection.createIndex({ name: 1 }) // Ascending index on the "name" field
5. What is sharding in MongoDB?
Answer: Sharding is the process of distributing data across multiple servers to handle large datasets and high throughput. MongoDB splits data into chunks and distributes them across shards.
Key components of sharding:
Shard: Holds data.
Config Server: Stores metadata about the sharded cluster.
Query Router (mongos): Routes client queries to the appropriate shard.
6. What is the difference between find() and aggregate() in MongoDB?
Answer:
find(): Retrieves documents based on a query. Example:
db.collection.find({ age: { $gt: 25 } })
aggregate(): Performs complex data processing, like grouping, sorting, or filtering. Example:
db.collection.aggregate([ { $match: { age: { $gt: 25 } } }, { $group: { _id: "$city", total: { $sum: 1 } } } ])
7. How does MongoDB ensure data consistency?
Answer: MongoDB ensures consistency through:
Write Concern: Specifies the level of acknowledgment for writes. Example:
{ w: 1 }
ensures acknowledgment by the primary.Read Concern: Specifies the level of isolation for reads. Example:
{ level: "majority" }
ensures the majority of nodes acknowledge the read.
8. What are the limitations of MongoDB?
Answer:
Limited support for complex transactions compared to RDBMS.
Consumes more storage due to BSON format.
Indexes can consume a lot of RAM.
Data redundancy in replication may increase costs.
9. How would you handle schema design in MongoDB?
Answer: Schema design in MongoDB should be based on the application's query patterns:
Use embedded documents for one-to-few relationships.
Use referencing for one-to-many relationships.
Avoid deeply nested documents as they can cause performance issues.
10. What is the purpose of the $lookup
operator in aggregation?
Answer: The $lookup
operator performs a left outer join to another collection in the same database. It is useful for combining data from multiple collections.
Example:
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
])
11. How does MongoDB handle transactions?
Answer: MongoDB supports multi-document ACID transactions since version 4.0. Transactions can span multiple operations on multiple documents.
Example:
const session = db.getMongo().startSession();
session.startTransaction();
try {
session.getDatabase("mydb").collection("accounts").updateOne(
{ accountId: 1 },
{ $inc: { balance: -100 } },
{ session }
);
session.getDatabase("mydb").collection("accounts").updateOne(
{ accountId: 2 },
{ $inc: { balance: 100 } },
{ session }
);
session.commitTransaction();
} catch (error) {
session.abortTransaction();
} finally {
session.endSession();
}
12. What are capped collections in MongoDB?
Answer: Capped collections are fixed-size collections that maintain insertion order and do not allow deletion or updates that increase document size. They are ideal for logging and real-time data.
Example:
db.createCollection("logs", { capped: true, size: 5242880, max: 5000 })
13. What is the purpose of $regex
in MongoDB?
Answer: The $regex
operator is used for pattern matching in strings.
Example:
db.collection.find({ name: { $regex: "^A", $options: "i" } }) // Matches names starting with "A", case insensitive
14. How do you monitor MongoDB performance?
Answer:
Monitoring tools: MongoDB Atlas, Ops Manager.
Commands: Use
db.stats()
ordb.serverStatus()
.Profiling: Enable profiling to capture slow queries.
db.setProfilingLevel(2)
15. How can you back up and restore a MongoDB database?
Answer:
Backup: Use
mongodump
to create a backup.mongodump --db mydb --out /backup/path
Restore: Use
mongorestore
to restore from a backup.mongorestore --db mydb /backup/path/mydb
๐ Stay Updated
Follow me for more design tips and tools! โจ
๐ GitHub: Follow me for more web development resources.
๐ LinkedIn: Connect with me for tips and tricks in coding.
โ๏ธ Medium: Follow me for in-depth articles on web development.
๐ฌ Substack: Dive into my newsletter for exclusive insights and updates: