Lesson 47 of 50 – MongoDB Interview Questions and Answers
94%

MongoDB Interview Questions and Answers

In this lesson, you will learn important MongoDB interview questions with simple answers. These questions cover MongoDB fundamentals, CRUD operations, query operators, indexes, aggregation, schema design, and performance.

1. Basic MongoDB Interview Questions

Q1. What is MongoDB?

MongoDB is a document-oriented NoSQL database that stores data in BSON documents. It supports flexible document structures, indexes, aggregation, and replication.

Q2. What is a NoSQL database?

A NoSQL database uses data models other than the traditional relational table model. MongoDB stores data in documents organized into collections.

Q3. What is the difference between SQL and MongoDB?
SQL Databases MongoDB
Data is commonly organized into tables. Data is organized into collections and documents.
Rows store records. BSON documents store records.
Relationships often use foreign keys and joins. Relationships can use embedded documents, references, and aggregation with $lookup.
Schema is commonly defined through tables and columns. Documents can have flexible structures, with optional schema validation.
Q4. What is a document in MongoDB?

A document is a set of field-value pairs stored in BSON format.

{
    name: "Rahul",
    age: 25,
    city: "Patna"
}
Q5. What is a collection?

A collection is a group of MongoDB documents. It is broadly comparable to a table in a relational database.

Q6. What is BSON?

BSON stands for Binary JSON. It is the binary-encoded document format MongoDB uses and supports types such as dates, ObjectIds, and numeric types.

Q7. What is the _id field?

The _id field uniquely identifies a document within a collection. MongoDB automatically generates an ObjectId when an inserted document does not provide an _id value.

Q8. What is ObjectId?

ObjectId is a BSON type commonly used for MongoDB document identifiers.

db.students.insertOne({
    name: "Amit",
    age: 22
})
Q9. What is MongoDB Compass?

MongoDB Compass is a graphical user interface for exploring collections, viewing documents, running queries, and managing indexes.

Q10. What is mongosh?

mongosh is the MongoDB Shell used to connect to MongoDB and execute database commands.

2. CRUD Interview Questions

Q11. What does CRUD mean?

CRUD stands for Create, Read, Update, and Delete. These are the four basic data operations.

Q12. How do you insert a document?
db.students.insertOne({
    name: "Rahul",
    age: 20
})
Q13. How do you insert multiple documents?
db.students.insertMany([
    { name: "Amit", age: 21 },
    { name: "Priya", age: 22 }
])
Q14. How do you find all documents?
db.students.find()
Q15. How do you find one document?
db.students.findOne({
    name: "Rahul"
})
Q16. How do you update a document?
db.students.updateOne(
    { name: "Rahul" },
    { $set: { age: 23 } }
)
Q17. What is the difference between updateOne() and updateMany()?

updateOne() updates at most one matching document, while updateMany() updates all documents that match the filter.

Q18. How do you delete one document?
db.students.deleteOne({
    name: "Rahul"
})
Q19. What is the difference between deleteOne() and deleteMany()?

deleteOne() deletes at most one matching document. deleteMany() deletes all matching documents.

Q20. What does $set do?

The $set update operator sets the specified field to a value and leaves other unspecified fields unchanged.

db.students.updateOne(
    { name: "Amit" },
    { $set: { city: "Gaya" } }
)

3. Query Operator Interview Questions

Q21. What is a query operator?

A query operator helps specify conditions when retrieving documents.

Q22. What is the $gt operator?

$gt means greater than.

db.students.find({
    age: { $gt: 18 }
})
Q23. What is the $lt operator?

$lt means less than.

db.students.find({
    age: { $lt: 25 }
})
Q24. What is the $gte operator?

$gte means greater than or equal to.

db.students.find({
    age: { $gte: 18 }
})
Q25. What is the $lte operator?

$lte means less than or equal to.

db.students.find({
    age: { $lte: 25 }
})
Q26. What is the $in operator?

$in matches documents where a field's value matches any value in the specified array.

db.students.find({
    city: { $in: ["Patna", "Gaya"] }
})
Q27. What is the $and operator?

$and matches documents that satisfy every condition in its array.

db.students.find({
    $and: [
        { age: { $gte: 18 } },
        { city: "Patna" }
    ]
})
Q28. What is the $or operator?

$or matches documents that satisfy at least one condition.

db.students.find({
    $or: [
        { city: "Patna" },
        { age: { $gt: 25 } }
    ]
})
Q29. What is projection?

Projection specifies which fields should be included or excluded in the query results.

db.students.find(
    {},
    { name: 1, age: 1, _id: 0 }
)
Q30. How do you sort documents?
// Ascending order
db.students.find().sort({ age: 1 })

// Descending order
db.students.find().sort({ age: -1 })

4. Index Interview Questions

Q31. What is an index in MongoDB?

An index is a data structure that can help MongoDB find documents more efficiently without scanning every document for many query patterns.

Q32. How do you create an index?
db.students.createIndex({
    name: 1
})
Q33. What is a unique index?

A unique index prevents duplicate indexed values, subject to MongoDB's unique-index rules.

db.students.createIndex(
    { student_id: 1 },
    { unique: true }
)
Q34. What is a compound index?

A compound index contains more than one field. Field order matters because it affects which queries and sorts the index can support.

db.students.createIndex({
    city: 1,
    age: -1
})
Q35. What is the disadvantage of too many indexes?

Indexes consume storage and increase the work required for inserts, updates, and deletes. They should be selected based on actual query needs.

Q36. How do you view indexes?
db.students.getIndexes()
Q37. How do you delete an index?
db.students.dropIndex("name_1")

Use the actual index name returned by getIndexes().

5. Aggregation Interview Questions

Q38. What is aggregation in MongoDB?

Aggregation processes documents through a pipeline of stages to filter, group, transform, and calculate results.

Q39. What is the $match stage?

$match filters documents according to specified conditions.

db.students.aggregate([
    { $match: { city: "Patna" } }
])
Q40. What is the $group stage?

$group groups documents by an expression and calculates values such as totals and averages.

db.students.aggregate([
    {
        $group: {
            _id: "$city",
            totalStudents: { $sum: 1 }
        }
    }
])
Q41. What does $sum do?

$sum adds numeric values or counts documents when used with the value 1 inside a group.

Q42. What does $avg do?

$avg calculates the average of numeric values in an aggregation group.

Q43. What is $lookup?

$lookup performs a left outer join with another collection and adds matching results as an array field.

db.orders.aggregate([
    {
        $lookup: {
            from: "customers",
            localField: "customer_id",
            foreignField: "customer_id",
            as: "customer_details"
        }
    }
])
Q44. What is $unwind?

$unwind deconstructs an array field, producing a separate pipeline document for each array element.

db.orders.aggregate([
    { $unwind: "$items" }
])

6. Advanced MongoDB Interview Questions

Q45. What is the difference between embedding and referencing?

Embedding stores related information inside a document. Referencing stores an identifier that points to related information in another document or collection.

Embedding can simplify reads when related data is usually accessed together. Referencing can be useful when related data is large, shared, or independently updated.

Q46. What is a replica set?

A replica set is a group of MongoDB servers that maintain the same dataset. It provides redundancy and supports automatic failover when configured correctly.

Q47. What is sharding?

Sharding distributes data across multiple machines to support larger datasets and workloads.

Q48. What is a transaction?

A transaction groups multiple database operations into a single atomic unit, so the operations either commit together or are rolled back together. Multi-document transactions require a supported deployment, such as a replica set or sharded cluster.

Q49. How can you investigate a slow query?

Use explain("executionStats"), inspect examined documents and index keys, check the query plan, and review indexes and query patterns.

db.students.find({
    city: "Patna"
}).explain("executionStats")
Q50. How can you improve MongoDB performance?

Common approaches include:

  • Create appropriate indexes.
  • Return only the required fields.
  • Use selective query filters.
  • Review aggregation pipelines.
  • Avoid unnecessarily large documents and results.
  • Measure queries with explain and monitoring tools.
  • Choose a schema suited to application access patterns.

7. Interview Preparation Tips

  • Practise each query in mongosh.
  • Understand why an operator is used, not just its syntax.
  • Be ready to explain indexes and query optimization.
  • Practise CRUD operations with a real collection.
  • Learn aggregation stages and how data flows through a pipeline.
  • Prepare examples of embedding, referencing, and transactions.
  • Explain trade-offs rather than assuming one design fits every application.

8. Quick Revision

Concept Purpose
Document Stores fields and values.
Collection Groups documents.
insertOne() Inserts one document.
find() Retrieves matching documents.
$set Sets specified field values.
createIndex() Creates an index.
$match Filters pipeline documents.
$group Groups and calculates values.
$lookup Combines matching data from another collection.
Replica set Provides data redundancy and failover.
Sharding Distributes data across machines.

🧠 Quick Quiz

1. Which format does MongoDB use to store documents internally?




2. Which stage groups documents in an aggregation pipeline?




3. Which feature distributes data across multiple machines?