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.
MongoDB is a document-oriented NoSQL database that stores data in BSON documents. It supports flexible document structures, indexes, aggregation, and replication.
A NoSQL database uses data models other than the traditional relational table model. MongoDB stores data in documents organized into collections.
| 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. |
A document is a set of field-value pairs stored in BSON format.
{
name: "Rahul",
age: 25,
city: "Patna"
}
A collection is a group of MongoDB documents. It is broadly comparable to a table in a relational database.
BSON stands for Binary JSON. It is the binary-encoded document format MongoDB uses and supports types such as dates, ObjectIds, and numeric types.
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.
ObjectId is a BSON type commonly used for MongoDB document identifiers.
db.students.insertOne({
name: "Amit",
age: 22
})
MongoDB Compass is a graphical user interface for exploring collections, viewing documents, running queries, and managing indexes.
mongosh is the MongoDB Shell used to
connect to MongoDB and execute database commands.
CRUD stands for Create, Read, Update, and Delete. These are the four basic data operations.
db.students.insertOne({
name: "Rahul",
age: 20
})
db.students.insertMany([
{ name: "Amit", age: 21 },
{ name: "Priya", age: 22 }
])
db.students.find()
db.students.findOne({
name: "Rahul"
})
db.students.updateOne(
{ name: "Rahul" },
{ $set: { age: 23 } }
)
updateOne() updates at most one matching
document, while updateMany() updates
all documents that match the filter.
db.students.deleteOne({
name: "Rahul"
})
deleteOne() deletes at most one matching
document. deleteMany() deletes all
matching documents.
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" } }
)
A query operator helps specify conditions when retrieving documents.
$gt means greater than.
db.students.find({
age: { $gt: 18 }
})
$lt means less than.
db.students.find({
age: { $lt: 25 }
})
$gte means greater than or equal to.
db.students.find({
age: { $gte: 18 }
})
$lte means less than or equal to.
db.students.find({
age: { $lte: 25 }
})
$in matches documents where a field's
value matches any value in the specified array.
db.students.find({
city: { $in: ["Patna", "Gaya"] }
})
$and matches documents that satisfy
every condition in its array.
db.students.find({
$and: [
{ age: { $gte: 18 } },
{ city: "Patna" }
]
})
$or matches documents that satisfy
at least one condition.
db.students.find({
$or: [
{ city: "Patna" },
{ age: { $gt: 25 } }
]
})
Projection specifies which fields should be included or excluded in the query results.
db.students.find(
{},
{ name: 1, age: 1, _id: 0 }
)
// Ascending order
db.students.find().sort({ age: 1 })
// Descending order
db.students.find().sort({ age: -1 })
An index is a data structure that can help MongoDB find documents more efficiently without scanning every document for many query patterns.
db.students.createIndex({
name: 1
})
A unique index prevents duplicate indexed values, subject to MongoDB's unique-index rules.
db.students.createIndex(
{ student_id: 1 },
{ unique: true }
)
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
})
Indexes consume storage and increase the work required for inserts, updates, and deletes. They should be selected based on actual query needs.
db.students.getIndexes()
db.students.dropIndex("name_1")
Use the actual index name returned by
getIndexes().
Aggregation processes documents through a pipeline of stages to filter, group, transform, and calculate results.
$match filters documents according to
specified conditions.
db.students.aggregate([
{ $match: { city: "Patna" } }
])
$group groups documents by an expression
and calculates values such as totals and averages.
db.students.aggregate([
{
$group: {
_id: "$city",
totalStudents: { $sum: 1 }
}
}
])
$sum adds numeric values or counts
documents when used with the value 1
inside a group.
$avg calculates the average of numeric
values in an aggregation group.
$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"
}
}
])
$unwind deconstructs an array field,
producing a separate pipeline document for each
array element.
db.orders.aggregate([
{ $unwind: "$items" }
])
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.
A replica set is a group of MongoDB servers that maintain the same dataset. It provides redundancy and supports automatic failover when configured correctly.
Sharding distributes data across multiple machines to support larger datasets and workloads.
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.
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")
Common approaches include:
mongosh.| 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. |
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?