MongoDB Interview Master
Level up your NoSQL skills with 100+ meticulously curated MongoDB questions. From basic CRUD to advanced cluster architecture and aggregation.
What is MongoDB?
BeginnerMongoDB is an open-source, document-oriented NoSQL database program. Instead of using tables and rows as in traditional relational databases, MongoDB uses JSON-...
Comprehensive Solution
What is a Document in MongoDB?
BeginnerA document is the basic unit of data in MongoDB, analogous to a row in an RDBMS. Documents are composed of field-and-value pairs and are stored in BSON (Binary ...
Comprehensive Solution
Mongo Shell / Code
{
"name": "John Doe",
"age": 30,
"interests": ["coding", "reading"]
}What is a Collection in MongoDB?
BeginnerA collection is a grouping of MongoDB documents. It is equivalent to a table in a relational database. Collections do not enforce a strict schema, although sche...
Comprehensive Solution
What is BSON?
BeginnerBSON stands for **Binary JSON**. It is a binary-encoded serialization of JSON-like documents. BSON extends the JSON model to provide additional data types (like...
Comprehensive Solution
What are the primary advantages of MongoDB?
BeginnerKey advantages include: 1. **Flexible Schema**: Documents in a collection can have different fields. 2. **Scalability**: Seamless horizontal scaling via shardin...
Comprehensive Solution
What is the '_id' field in MongoDB?
BeginnerThe `_id` field is a unique identifier required for every document in a collection. If you don't provide one, MongoDB automatically generates an `ObjectId` for ...
Comprehensive Solution
What is an ObjectId in MongoDB?
BeginnerAn ObjectId is a 12-byte BSON type that is unique within a collection. It consists of: - A 4-byte timestamp (seconds since Unix epoch). - A 5-byte random value....
Comprehensive Solution
How do you create a database in MongoDB?
BeginnerIn the MongoDB Shell, you use the `use` command. MongoDB will not actually create the database until you insert data into it.
Comprehensive Solution
Mongo Shell / Code
use interview_dbHow do you insert a document into a collection?
BeginnerYou use `insertOne()` for a single document or `insertMany()` for multiple documents.
Comprehensive Solution
Mongo Shell / Code
db.users.insertOne({ name: "Alice", age: 25 });How do you find all documents in a collection?
BeginnerYou use the `find()` method. To make the output readable, you can append `.pretty()` (in older shells) or just run it.
Comprehensive Solution
Mongo Shell / Code
db.users.find();What is the difference between MongoDB and RDBMS?
Beginner- **RDBMS**: Structured (Tables/Rows), uses SQL, strict schema, joins are common, vertically scalable. - **MongoDB**: Unstructured (Collections/Documents), uses...
Comprehensive Solution
What is Namespace in MongoDB?
BeginnerA namespace is the concatenation of the database name and the collection name (e.g., `dbName.collectionName`). Together they uniquely identify a collection.
Comprehensive Solution
How do you update a document in MongoDB?
BeginnerYou use `updateOne()`, `updateMany()`, or `replaceOne()`. Use the `$set` operator to update specific fields.
Comprehensive Solution
Mongo Shell / Code
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
);How do you delete a document?
BeginnerYou use `deleteOne()` or `deleteMany()`.
Comprehensive Solution
Mongo Shell / Code
db.users.deleteOne({ name: "Alice" });What is the purpose of the '$set' operator?
BeginnerThe `$set` operator replaces the value of a field with the specified value. If the field does not exist, `$set` adds a new field with the specified value.
Comprehensive Solution
What is the difference between findOne() and find()?
Beginner- **find()**: Returns a cursor to all documents that match the query criteria. - **findOne()**: Returns only the first document that matches the query criteria.
Comprehensive Solution
How do you limit the number of results in MongoDB?
BeginnerYou use the `.limit()` method on the cursor.
Comprehensive Solution
Mongo Shell / Code
db.users.find().limit(5);How do you sort results in MongoDB?
BeginnerYou use the `.sort()` method. Use **1** for ascending and **-1** for descending.
Comprehensive Solution
Mongo Shell / Code
db.users.find().sort({ age: 1 }); // Youngest firstWhat is Projection in MongoDB?
BeginnerProjection is the process of selecting only the necessary fields from a document rather than the entire document. You pass a second argument to `find()`.
Comprehensive Solution
Mongo Shell / Code
db.users.find({}, { name: 1, _id: 0 }); // Show only nameWhat is the use of the '$in' operator?
BeginnerThe `$in` operator selects the documents where the value of a field equals any value in the specified array.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ age: { $in: [20, 25, 30] } });How do you count the number of documents in a collection?
BeginnerYou use `countDocuments()` or `estimatedDocumentCount()`.
Comprehensive Solution
Mongo Shell / Code
db.users.countDocuments({ age: { $gt: 18 } });What is an Index in MongoDB?
BeginnerIndexes are special data structures that store a small portion of the collection's data set in a form that is easy to traverse. They improve the efficiency of s...
Comprehensive Solution
What is a GridFS?
BeginnerGridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16 MB. It divides a file into chunks and stores each chun...
Comprehensive Solution
What is the default port for MongoDB?
BeginnerThe default port for MongoDB is **27017**.
Comprehensive Solution
What is the command to see all databases?
BeginnerYou use the `show dbs` command (or `show databases`).
Comprehensive Solution
Mongo Shell / Code
show dbsHow do you perform a simple count in MongoDB?
IntermediateUse the `countDocuments()` method for an accurate count or `estimatedDocumentCount()` for a faster but potentially less accurate estimate.
Comprehensive Solution
Mongo Shell / Code
db.users.countDocuments({ status: "active" });What is an Aggregation Pipeline in MongoDB?
IntermediateThe aggregation pipeline is a framework for data transformation. Documents enter a multi-stage pipeline that transforms them into aggregated results. Common sta...
Comprehensive Solution
Mongo Shell / Code
db.orders.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
]);Explain the '$match' stage in Aggregation.
IntermediateThe `$match` stage filters the documents based on specific criteria. It is recommended to use `$match` early in the pipeline to reduce the number of documents p...
Comprehensive Solution
Explain the '$group' stage in Aggregation.
IntermediateThe `$group` stage groups input documents by a specified identifier expression and applies accumulator expressions (like `$sum`, `$avg`, `$push`) to each group.
Comprehensive Solution
Mongo Shell / Code
{ $group: { _id: "$category", totalStock: { $sum: "$stock" } } }What is the difference between Embedding and Referencing in Schema Design?
Intermediate- **Embedding**: Storing related data in a single document. Good for high-read performance and 'one-to-few' relationships. - **Referencing**: Storing references...
Comprehensive Solution
What is a TTL (Time-To-Live) Index?
IntermediateA TTL index is a special index that automatically removes documents from a collection after a certain amount of time. It is useful for data like machine-generat...
Comprehensive Solution
Mongo Shell / Code
db.logs.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 });What is a Capped Collection?
IntermediateCapped collections are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order. They work lik...
Comprehensive Solution
What is the use of the '$lookup' operator?
IntermediateThe `$lookup` stage performs a left outer join to an unsharded collection in the *same* database to filter in documents from the "joined" collection for process...
Comprehensive Solution
Mongo Shell / Code
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "product_id",
foreignField: "_id",
as: "product_details"
}
}
]);How do you handle Transactions in MongoDB?
IntermediateMongoDB supports multi-document ACID transactions since version 4.0 (for replica sets) and 4.2 (for sharded clusters). You must use a `session` to begin, commit...
Comprehensive Solution
What are Covered Queries?
IntermediateA covered query is a query where all the fields in the query are part of an index, and all the fields returned in the results are also part of the same index. M...
Comprehensive Solution
Explain the Concept of Sharding.
IntermediateSharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput ...
Comprehensive Solution
What is a Shard Key?
IntermediateA shard key is a field or fields that determine the distribution of documents among the cluster's shards. Choosing a good shard key (with high cardinality and e...
Comprehensive Solution
What is a Replica Set?
IntermediateA replica set is a group of `mongod` instances that maintain the same data set. It provides redundancy and high availability. One node is the **Primary** (recei...
Comprehensive Solution
What is a Write Concern in MongoDB?
IntermediateWrite concern describes the level of acknowledgment requested from MongoDB for write operations to a standalone `mongod` or to replica sets or to sharded cluste...
Comprehensive Solution
What is a Read Preference?
IntermediateRead preference describes how MongoDB clients route read operations to the members of a replica set. Common preferences include `primary` (default), `primaryPre...
Comprehensive Solution
What is the purpose of the '$unwind' stage?
IntermediateThe `$unwind` stage deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with ...
Comprehensive Solution
Mongo Shell / Code
{ $unwind: "$tags" }Explain the '$facet' stage in aggregation.
IntermediateThe `$facet` stage allows you to process multiple aggregation pipelines within a single stage on the same set of input documents. Each sub-pipeline has its own ...
Comprehensive Solution
What is the difference between '$addFields' and '$project'?
Intermediate- **$project**: Reshapes each document in the stream, such as by adding new fields or removing existing fields. You must explicitly include all fields you want ...
Comprehensive Solution
What is a Compound Index?
IntermediateA compound index is an index where a single index structure holds references to multiple fields within a collection's documents. The order of fields in a compou...
Comprehensive Solution
Mongo Shell / Code
db.users.createIndex({ "lastName": 1, "firstName": 1 });What is a Partial Index?
IntermediatePartial indexes only index documents in a collection that meet a specified filter expression. This reduces the index size and performance overhead for index upd...
Comprehensive Solution
Mongo Shell / Code
db.users.createIndex(
{ "email": 1 },
{ partialFilterExpression: { "age": { $gt: 18 } } }
);How do you view index usage in MongoDB?
IntermediateYou can use the `.explain("executionStats")` method to see if an index was used for a particular query.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ email: "test@test.com" }).explain("executionStats");What is the 'oplog' (Operations Log)?
IntermediateThe oplog is a capped collection in the `local` database that keeps a rolling record of all data-modifying operations. Secondary members of a replica set use th...
Comprehensive Solution
What is an Arbiter in a Replica Set?
IntermediateAn arbiter is a `mongod` instance that is part of a replica set but does not maintain a copy of the data set. Its purpose is to participate in elections to brea...
Comprehensive Solution
How to backup and restore MongoDB databases?
IntermediateCommon tools are `mongodump` (binary backup) and `mongoexport` (CSV/JSON backup). Use `mongorestore` and `mongoimport` to restore.
Comprehensive Solution
Mongo Shell / Code
mongodump --db=interview_db --out=/backups/What is the use of the '$out' stage in aggregation?
IntermediateThe `$out` stage writes the resulting documents of the aggregation pipeline to a specified collection. If the collection exists, `$out` replaces it with the res...
Comprehensive Solution
Mongo Shell / Code
{ $out: "agg_results" }Explain the difference between 2d and 2dsphere indexes.
Advanced- **2d**: For data stored as points on a two-dimensional flat surface (Euclidean geometry). - **2dsphere**: For data that is stored as GeoJSON objects or legacy...
Comprehensive Solution
How does MongoDB handle data consistency?
AdvancedMongoDB follows the **CAP theorem** (Consistency, Availability, Partition tolerance). By default, it is a CP system. It ensures consistency via the Primary node...
Comprehensive Solution
What is Joins in MongoDB?
AdvancedMongoDB is designed to avoid joins where possible by using embedding. However, SQL-like joins can be performed across non-sharded collections using the `$lookup...
Comprehensive Solution
Explain the Working of 'Election' in Replica Sets.
AdvancedWhen a Primary becomes unavailable, the Secondaries hold an election to choose a new Primary. A member needs a majority of votes to become the Primary. Arbiters...
Comprehensive Solution
What are Change Streams?
AdvancedChange streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to ...
Comprehensive Solution
Explain the use of 'Hint' in MongoDB.
AdvancedThe `.hint()` method forces the query optimizer to use a specific index. This is used when the optimizer chooses a less efficient index or a collection scan.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ age: 25 }).hint({ age: 1 });What is the 'wiredTiger' storage engine?
AdvancedWiredTiger is the default storage engine for MongoDB since version 3.2. Features include document-level concurrency control, compression (Snappy, Zlib), and che...
Comprehensive Solution
What are Orphaned Documents?
AdvancedIn a sharded cluster, orphaned documents are those that exist on a shard but technically belong to a chunk that has migrated to another shard. This can happen i...
Comprehensive Solution
What is the 'Journal' in MongoDB?
AdvancedThe journal is a log that records all write operations before they are applied to the data files. It ensures that MongoDB can recover to a consistent state if t...
Comprehensive Solution
Explain the 'Working Set' concept.
AdvancedThe working set is the portion of data (documents and indexes) that the application uses frequently and must fit in RAM for optimal performance. If the working ...
Comprehensive Solution
What is a Sparse Index?
AdvancedA sparse index only contains entries for documents that have the indexed field, even if the index field contains a null value. It skips documents that do not ha...
Comprehensive Solution
Mongo Shell / Code
db.users.createIndex({ "twitter_handle": 1 }, { sparse: true });Explain 'Mongoose' in the context of MongoDB.
AdvancedMongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model application data, with built-in v...
Comprehensive Solution
What is the 16MB Document Limit?
AdvancedSingle BSON documents in MongoDB are limited to 16 megabytes. This limit prevents documents from growing too large and consuming excessive RAM or bandwidth. Lar...
Comprehensive Solution
Explain 'Horizontal' vs 'Vertical' Scaling.
Advanced- **Vertical**: Adding more CPU, RAM, or storage to a single server. Limited by hardware capacity. - **Horizontal**: Adding more servers and distributing data a...
Comprehensive Solution
What is 'Read Concern' in MongoDB?
AdvancedRead concern controls the consistency and isolation properties of the data read from the replica set or sharded cluster. Examples: `local`, `majority`, `snapsho...
Comprehensive Solution
Explain 'Map-Reduce' in MongoDB.
AdvancedMap-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. It is generally replaced by the Aggregation Pipeli...
Comprehensive Solution
What are 'Views' in MongoDB?
AdvancedA MongoDB view is a read-only queryable object whose contents are defined by an aggregation pipeline. They do not store data themselves but are computed on dema...
Comprehensive Solution
Mongo Shell / Code
db.createView("activeUsers", "users", [{ $match: { status: "active" } }]);What is 'Causal Consistency'?
AdvancedCausal consistency ensures that operations are executed in a way that respects the sequence of causal dependencies. For example, if operation A happened before ...
Comprehensive Solution
How to tune MongoDB performance?
Advanced1. Create appropriate indexes. 2. Use Projection to return only needed fields. 3. Ensure the working set fits in RAM. 4. Use the Aggregation Pipeline for proces...
Comprehensive Solution
What is 'Write Strategy' for Sharding?
AdvancedSharding write strategies include **Hashed Sharding** (even distribution) and **Ranged Sharding** (efficient range queries). Choosing depends on application acc...
Comprehensive Solution
Explain 'Balancing' in Sharded Clusters.
AdvancedThe balancer is a background process that monitors the number of chunks on each shard. If the imbalance exceeds a threshold, the balancer migrates chunks betwee...
Comprehensive Solution
What are 'Sessions' in MongoDB?
AdvancedSessions provide a context for operations, enabling features like ACID transactions and causal consistency. A session tracks operations and ensures they are gro...
Comprehensive Solution
How to monitor MongoDB?
AdvancedUse MongoDB's `mongostat` and `mongotop` CLI tools, or cloud solutions like **MongoDB Atlas** monitoring and Cloud Manager.
Comprehensive Solution
What is 'Schema Validation'?
AdvancedMongoDB allows you to define validation rules for collections (JSON Schema). This ensures that documents inserted or updated conform to a specific structure.
Comprehensive Solution
Mongo Shell / Code
db.createCollection("students", { validator: { $jsonSchema: { ... } } });Explain 'Disk Compression' in WiredTiger.
AdvancedWiredTiger provides block-level compression for collections and indexes. This reduces storage footprint significantly at the cost of some CPU usage.
Comprehensive Solution
Scenario: How to find top 5 most expensive orders using aggregation?
ScenarioUse `$sort` followed by `$limit`.
Comprehensive Solution
Mongo Shell / Code
db.orders.aggregate([
{ $sort: { totalAmount: -1 } },
{ $limit: 5 }
]);Scenario: How to calculate total revenue per category?
ScenarioUse the `$group` stage with the `$sum` accumulator.
Comprehensive Solution
Mongo Shell / Code
db.sales.aggregate([
{ $group: { _id: "$category", revenue: { $sum: "$price" } } }
]);Scenario: How to find users who have exactly 3 tags?
ScenarioUse the `$size` operator in the query.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ tags: { $size: 3 } });Scenario: How to remove a field from all documents in a collection?
ScenarioUse `updateMany()` with the `$unset` operator.
Comprehensive Solution
Mongo Shell / Code
db.users.updateMany({}, { $unset: { oldField: "" } });Scenario: How to find documents where an array field contains a specific value?
ScenarioYou can query the array field directly; MongoDB will match if any element in the array matches.
Comprehensive Solution
Mongo Shell / Code
db.posts.find({ tags: "mongodb" });Scenario: How to perform a 'Full Text Search' for the word 'database'?
ScenarioFirst, create a `text` index on the field(s), then use the `$text` operator.
Comprehensive Solution
Mongo Shell / Code
db.articles.createIndex({ content: "text" });
db.articles.find({ $text: { $search: "database" } });Scenario: How to find documents with a field that is NOT null and exists?
ScenarioUse `$ne: null` and `$exists: true`.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ email: { $ne: null, $exists: true } });Scenario: How to increment a counter field by 1?
ScenarioUse the `$inc` operator in an update operation.
Comprehensive Solution
Mongo Shell / Code
db.stats.updateOne({ _id: 1 }, { $inc: { views: 1 } });Scenario: How to find documents where field A is greater than field B?
ScenarioUse the `$expr` operator to use aggregation expressions within a regular query.
Comprehensive Solution
Mongo Shell / Code
db.products.find({ $expr: { $gt: [ "$price", "$cost" ] } });Scenario: How to rename a field across all documents?
ScenarioUse `updateMany()` with the `$rename` operator.
Comprehensive Solution
Mongo Shell / Code
db.users.updateMany({}, { $rename: { "oldName": "newName" } });Scenario: How to push an item to an array only if it doesn't already exist?
ScenarioUse the `$addToSet` operator.
Comprehensive Solution
Mongo Shell / Code
db.users.updateOne({ _id: 1 }, { $addToSet: { tags: "new_tag" } });Scenario: How to get the current date in an aggregation pipeline?
ScenarioUse the `$$NOW` system variable.
Comprehensive Solution
Mongo Shell / Code
db.logs.aggregate([
{ $addFields: { processedAt: "$$NOW" } }
]);Scenario: How to find documents that were created in the last 24 hours?
ScenarioCalculate the timestamp and use `$gte`.
Comprehensive Solution
Mongo Shell / Code
const yesterday = new Date(Date.now() - 24*60*60*1000);
db.logs.find({ createdAt: { $gte: yesterday } });Scenario: How to 'Join' users with their posts using aggregation?
ScenarioUse the `$lookup` stage.
Comprehensive Solution
Mongo Shell / Code
db.users.aggregate([
{
$lookup: {
from: "posts",
localField: "_id",
foreignField: "author_id",
as: "user_posts"
}
}
]);Scenario: How to filter a 'joined' array from $lookup?
ScenarioUse the complex `$lookup` syntax (pipeline) or a subsequent `$filter` stage.
Comprehensive Solution
Mongo Shell / Code
db.users.aggregate([
{
$lookup: {
from: "posts",
let: { userId: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$author_id", "$$userId"] }, status: "published" } }
],
as: "live_posts"
}
}
]);Scenario: How to flatten an array of objects into separate documents?
ScenarioUse the `$unwind` stage.
Comprehensive Solution
Mongo Shell / Code
db.orders.aggregate([{ $unwind: "$items" }]);Scenario: How to find the average age of users per city, but only for cities with more than 10 users?
ScenarioGroup, then use `$match` (equivalent to SQL HAVING).
Comprehensive Solution
Mongo Shell / Code
db.users.aggregate([
{ $group: { _id: "$city", avgAge: { $avg: "$age" }, count: { $sum: 1 } } },
{ $match: { count: { $gt: 10 } } }
]);Scenario: How to update multiple fields in a single document based on conditions?
ScenarioUse an aggregation-based update (available in MongoDB 4.2+).
Comprehensive Solution
Mongo Shell / Code
db.users.updateOne(
{ _id: 1 },
[{ $set: { status: { $cond: { if: { $gt: ["$score", 50] }, then: "pass", else: "fail" } } } }]
);Scenario: How to pull (remove) all occurrences of 'error' from an array?
ScenarioUse the `$pull` operator.
Comprehensive Solution
Mongo Shell / Code
db.logs.updateMany({}, { $pull: { tags: "error" } });Scenario: How to find documents where a field is of a specific type (e.g., String)?
ScenarioUse the `$type` operator.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ age: { $type: "string" } }); // Oops, age is string hereScenario: How to perform a 'Dry Run' of a deletion?
ScenarioRun the same query with `find()` first to see which documents will be affected.
Comprehensive Solution
Mongo Shell / Code
db.users.find({ inactive: true }).map(u => u._id); // Preview IDsScenario: How to get the last 10 log entries?
ScenarioSort by `_id` or timestamp descending and limit to 10.
Comprehensive Solution
Mongo Shell / Code
db.logs.find().sort({ _id: -1 }).limit(10);Scenario: How to search for coordinates within a 5km radius of a point?
ScenarioUse the `$near` operator with `$maxDistance` (in meters).
Comprehensive Solution
Mongo Shell / Code
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [ -73.96, 40.78 ] },
$maxDistance: 5000
}
}
});Scenario: You need a schema where one document contains 'many' others, potentially causing size issues. Solution?
ScenarioMove to a 'Linking' (Referencing) model or use 'Bucket' pattern (e.g., one document per 100 related items) to stay below 16MB and keep queries efficient.
Comprehensive Solution
How to export a collection to a JSON file?
ScenarioUse the `mongoexport` command-line utility.
Comprehensive Solution
Mongo Shell / Code
mongoexport --db=interview_db --collection=users --out=users.json