100 Frequently asked MongoDB Questions with Explanation

MongoDB is widely used in modern applications due to its scalability, flexibility, and performance. Below are 100 important MongoDB interview questions with detailed answers.

1. What is MongoDB, and how is it different from SQL databases?

MongoDB is a NoSQL document-oriented database that stores data in JSON-like BSON format.
Differences from SQL Databases:

  • Schema-less (Flexible structure, unlike fixed tables in SQL).
  • Uses Collections & Documents (Instead of Tables & Rows).
  • No Joins (Uses embedding or referencing instead).
  • Horizontally Scalable (SQL scales vertically).

2. What is a Collection and Document in MongoDB?

  • Collection → Equivalent to a table in SQL, but schema-less.
  • Document → A record inside a collection, stored as BSON (Binary JSON).

Example Document:

{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "Alice",
  "age": 25,
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

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

Using insertOne() or insertMany():

db.users.insertOne({ name: "Alice", age: 25 });
db.users.insertMany([{ name: "Bob", age: 30 }, { name: "Charlie", age: 35 }]);

4. How do you query documents in MongoDB?

Using find() method:

db.users.find(); // Fetch all users
db.users.find({ age: { $gt: 30 } }); // Fetch users older than 30

5. How do you update a document in MongoDB?

Using updateOne() or updateMany():

db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } }); // Updates Alice's age
db.users.updateMany({}, { $inc: { age: 1 } }); // Increments age for all users

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

Indexes improve query performance by reducing the amount of data scanned.
Example: Creating an index on the name field:

db.users.createIndex({ name: 1 }); // Ascending index on name field

7. How does MongoDB handle relationships between data?

MongoDB supports two relationship methods:

  1. Embedding (Storing related data inside a document, best for one-to-few relationships).
  2. Referencing (Storing ObjectId references to another collection, best for large relationships).

Example Referencing (Normalization):

{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "Alice",
  "order_ids": [ObjectId("607f1f77bcf86cd799439012")]
}

8. What is Aggregation in MongoDB?

Aggregation is used for data transformation and computation, similar to SQL GROUP BY.
Example: Find the average age of users:

db.users.aggregate([
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
]);

9. What is Sharding in MongoDB?

Sharding divides large datasets across multiple servers to ensure horizontal scaling.

  • Uses a shard key to distribute data efficiently.
  • Improves performance for big data applications.

Explain replication in MongoDB.

Replication ensures high availability and data redundancy using replica sets—a group of MongoDB instances with the same data. One node is the primary (handles writes), while others are secondaries (replicate data, handle reads). If the primary fails, a secondary is elected as the new primary. Example :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "localhost:27017" }] });
rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "localhost:27017" }] });
rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "localhost:27017" }] });

What is an index in MongoDB, and why is it important?

An index is a data structure that improves query performance by allowing faster lookups on specific fields. Without indexes, MongoDB scans every document (collection scan), which is slow for large datasets.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
db.collection.createIndex({ "name": 1 }); // 1 for ascending, -1 for descending
db.collection.createIndex({ "name": 1 }); // 1 for ascending, -1 for descending
db.collection.createIndex({ "name": 1 }); // 1 for ascending, -1 for descending

10. How does MongoDB ensure data consistency and durability?

MongoDB ensures data integrity using:

  • Write Concern → Controls acknowledgment levels for writes.
  • Journaling → Prevents data loss by logging writes.
  • Replication → Keeps multiple copies of data across servers.

Example of Write Concern:

db.users.insertOne({ name: "Alice" }, { writeConcern: { w: "majority" } });

What is the difference between insert(), save(), and update() in MongoDB?

  • insert(): Adds a new document to a collection (e.g., db.collection.insertOne({ “key”: “value” })).
  • save(): Inserts a document if no _id exists; otherwise, it updates the existing document (deprecated in newer drivers).
  • update(): Modifies existing documents based on a query (e.g., db.collection.updateOne({ “name”: “John” }, { $set: { “age”: 26 } })).

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *