MongoDB Interview Master

Level up your NoSQL skills with 100+ meticulously curated MongoDB questions. From basic CRUD to advanced cluster architecture and aggregation.

0 / 100 MasteredHigh PerformanceSharding & Scaling
Showing 100 expert-verified results in All Questions category.
1
What is MongoDB?
Beginner

MongoDB 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
MongoDB is an open-source, document-oriented NoSQL database program. Instead of using tables and rows as in traditional relational databases, MongoDB uses JSON-like documents with optional schemas (BSON). It is designed for scalability, high performance, and high availability.
Beginner
2
What is a Document in MongoDB?
Beginner

A 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
A 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 JSON) format.
Mongo Shell / Code
{
  "name": "John Doe",
  "age": 30,
  "interests": ["coding", "reading"]
}
Beginner
3
What is a Collection in MongoDB?
Beginner

A 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
A 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 schema validation is possible.
Beginner
4
What is BSON?
Beginner

BSON 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
BSON 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 Date and BinData) and to be more efficient for storage and scanning.
Beginner
5
What are the primary advantages of MongoDB?
Beginner

Key advantages include: 1. **Flexible Schema**: Documents in a collection can have different fields. 2. **Scalability**: Seamless horizontal scaling via shardin...

Comprehensive Solution
Key advantages include: 1. **Flexible Schema**: Documents in a collection can have different fields. 2. **Scalability**: Seamless horizontal scaling via sharding. 3. **High Performance**: Optimized for fast reads and writes. 4. **Rich Query Language**: Supports aggregation, geospatial queries, and text search. 5. **High Availability**: Built-in replication via Replica Sets.
Beginner
6
What is the '_id' field in MongoDB?
Beginner

The `_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
The `_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 it. It acts as the primary key for the document.
Beginner
7
What is an ObjectId in MongoDB?
Beginner

An 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
An 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. - A 3-byte incrementing counter.
Beginner
8
How do you create a database in MongoDB?
Beginner

In the MongoDB Shell, you use the `use` command. MongoDB will not actually create the database until you insert data into it.

Comprehensive Solution
In the MongoDB Shell, you use the `use` command. MongoDB will not actually create the database until you insert data into it.
Mongo Shell / Code
use interview_db
Beginner
9
How do you insert a document into a collection?
Beginner

You use `insertOne()` for a single document or `insertMany()` for multiple documents.

Comprehensive Solution
You use `insertOne()` for a single document or `insertMany()` for multiple documents.
Mongo Shell / Code
db.users.insertOne({ name: "Alice", age: 25 });
Beginner
10
How do you find all documents in a collection?
Beginner

You use the `find()` method. To make the output readable, you can append `.pretty()` (in older shells) or just run it.

Comprehensive Solution
You use the `find()` method. To make the output readable, you can append `.pretty()` (in older shells) or just run it.
Mongo Shell / Code
db.users.find();
Beginner
11
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
- **RDBMS**: Structured (Tables/Rows), uses SQL, strict schema, joins are common, vertically scalable. - **MongoDB**: Unstructured (Collections/Documents), uses MQL (MongoDB Query Language), dynamic schema, embedding/linking instead of joins, horizontally scalable.
Beginner
12
What is Namespace in MongoDB?
Beginner

A namespace is the concatenation of the database name and the collection name (e.g., `dbName.collectionName`). Together they uniquely identify a collection.

Comprehensive Solution
A namespace is the concatenation of the database name and the collection name (e.g., `dbName.collectionName`). Together they uniquely identify a collection.
Beginner
13
How do you update a document in MongoDB?
Beginner

You use `updateOne()`, `updateMany()`, or `replaceOne()`. Use the `$set` operator to update specific fields.

Comprehensive Solution
You use `updateOne()`, `updateMany()`, or `replaceOne()`. Use the `$set` operator to update specific fields.
Mongo Shell / Code
db.users.updateOne(
  { name: "Alice" }, 
  { $set: { age: 26 } }
);
Beginner
14
How do you delete a document?
Beginner

You use `deleteOne()` or `deleteMany()`.

Comprehensive Solution
You use `deleteOne()` or `deleteMany()`.
Mongo Shell / Code
db.users.deleteOne({ name: "Alice" });
Beginner
15
What is the purpose of the '$set' operator?
Beginner

The `$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
The `$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.
Beginner
16
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
- **find()**: Returns a cursor to all documents that match the query criteria. - **findOne()**: Returns only the first document that matches the query criteria.
Beginner
17
How do you limit the number of results in MongoDB?
Beginner

You use the `.limit()` method on the cursor.

Comprehensive Solution
You use the `.limit()` method on the cursor.
Mongo Shell / Code
db.users.find().limit(5);
Beginner
18
How do you sort results in MongoDB?
Beginner

You use the `.sort()` method. Use **1** for ascending and **-1** for descending.

Comprehensive Solution
You use the `.sort()` method. Use **1** for ascending and **-1** for descending.
Mongo Shell / Code
db.users.find().sort({ age: 1 }); // Youngest first
Beginner
19
What is Projection in MongoDB?
Beginner

Projection 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
Projection is the process of selecting only the necessary fields from a document rather than the entire document. You pass a second argument to `find()`.
Mongo Shell / Code
db.users.find({}, { name: 1, _id: 0 }); // Show only name
Beginner
20
What is the use of the '$in' operator?
Beginner

The `$in` operator selects the documents where the value of a field equals any value in the specified array.

Comprehensive Solution
The `$in` operator selects the documents where the value of a field equals any value in the specified array.
Mongo Shell / Code
db.users.find({ age: { $in: [20, 25, 30] } });
Beginner
21
How do you count the number of documents in a collection?
Beginner

You use `countDocuments()` or `estimatedDocumentCount()`.

Comprehensive Solution
You use `countDocuments()` or `estimatedDocumentCount()`.
Mongo Shell / Code
db.users.countDocuments({ age: { $gt: 18 } });
Beginner
22
What is an Index in MongoDB?
Beginner

Indexes 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
Indexes 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 search queries significantly.
Beginner
23
What is a GridFS?
Beginner

GridFS 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
GridFS 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 chunk as a separate document.
Beginner
24
What is the default port for MongoDB?
Beginner

The default port for MongoDB is **27017**.

Comprehensive Solution
The default port for MongoDB is **27017**.
Beginner
25
What is the command to see all databases?
Beginner

You use the `show dbs` command (or `show databases`).

Comprehensive Solution
You use the `show dbs` command (or `show databases`).
Mongo Shell / Code
show dbs
Beginner
26
How do you perform a simple count in MongoDB?
Intermediate

Use the `countDocuments()` method for an accurate count or `estimatedDocumentCount()` for a faster but potentially less accurate estimate.

Comprehensive Solution
Use the `countDocuments()` method for an accurate count or `estimatedDocumentCount()` for a faster but potentially less accurate estimate.
Mongo Shell / Code
db.users.countDocuments({ status: "active" });
Intermediate
27
What is an Aggregation Pipeline in MongoDB?
Intermediate

The aggregation pipeline is a framework for data transformation. Documents enter a multi-stage pipeline that transforms them into aggregated results. Common sta...

Comprehensive Solution
The aggregation pipeline is a framework for data transformation. Documents enter a multi-stage pipeline that transforms them into aggregated results. Common stages include `$match`, `$group`, `$sort`, and `$project`.
Mongo Shell / Code
db.orders.aggregate([
  { $match: { status: "A" } },
  { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
]);
Intermediate
28
Explain the '$match' stage in Aggregation.
Intermediate

The `$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
The `$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 processed in subsequent stages.
Intermediate
29
Explain the '$group' stage in Aggregation.
Intermediate

The `$group` stage groups input documents by a specified identifier expression and applies accumulator expressions (like `$sum`, `$avg`, `$push`) to each group.

Comprehensive Solution
The `$group` stage groups input documents by a specified identifier expression and applies accumulator expressions (like `$sum`, `$avg`, `$push`) to each group.
Mongo Shell / Code
{ $group: { _id: "$category", totalStock: { $sum: "$stock" } } }
Intermediate
30
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
- **Embedding**: Storing related data in a single document. Good for high-read performance and 'one-to-few' relationships. - **Referencing**: Storing references (like IDs) to related documents in other collections. Good for 'one-to-many' or 'many-to-many' relationships to avoid document size limits.
Intermediate
31
What is a TTL (Time-To-Live) Index?
Intermediate

A 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
A 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-generated event data, logs, and session information.
Mongo Shell / Code
db.logs.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 });
Intermediate
32
What is a Capped Collection?
Intermediate

Capped collections are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order. They work lik...

Comprehensive Solution
Capped collections are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order. They work like a circular buffer: once the collection fills its allocated space, it makes room for new documents by overwriting the oldest ones.
Intermediate
33
What is the use of the '$lookup' operator?
Intermediate

The `$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
The `$lookup` stage performs a left outer join to an unsharded collection in the *same* database to filter in documents from the "joined" collection for processing.
Mongo Shell / Code
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "product_id",
      foreignField: "_id",
      as: "product_details"
    }
  }
]);
Intermediate
34
How do you handle Transactions in MongoDB?
Intermediate

MongoDB 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
MongoDB 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, and abort transactions.
Intermediate
35
What are Covered Queries?
Intermediate

A 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
A 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. MongoDB can fulfill the query using only the index, without looking at the actual documents.
Intermediate
36
Explain the Concept of Sharding.
Intermediate

Sharding 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
Sharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations by splitting data into chunks and distributing them across 'shards'.
Intermediate
37
What is a Shard Key?
Intermediate

A 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
A 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 even distribution) is critical for performance.
Intermediate
38
What is a Replica Set?
Intermediate

A 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
A 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** (receives all writes), and the others are **Secondaries** (replicate data and provide reads).
Intermediate
39
What is a Write Concern in MongoDB?
Intermediate

Write 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
Write concern describes the level of acknowledgment requested from MongoDB for write operations to a standalone `mongod` or to replica sets or to sharded clusters. Example: `w: 1` (Acknowledge from Primary), `w: "majority"` (Acknowledge from majority of nodes).
Intermediate
40
What is a Read Preference?
Intermediate

Read preference describes how MongoDB clients route read operations to the members of a replica set. Common preferences include `primary` (default), `primaryPre...

Comprehensive Solution
Read preference describes how MongoDB clients route read operations to the members of a replica set. Common preferences include `primary` (default), `primaryPreferred`, `secondary`, and `nearest`.
Intermediate
41
What is the purpose of the '$unwind' stage?
Intermediate

The `$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
The `$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 the value of the array field replaced by the element.
Mongo Shell / Code
{ $unwind: "$tags" }
Intermediate
42
Explain the '$facet' stage in aggregation.
Intermediate

The `$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
The `$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 field in the output document.
Intermediate
43
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
- **$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 to keep. - **$addFields**: Adds new fields to documents. Similar to `$project`, but it automatically includes all existing fields from the input documents.
Intermediate
44
What is a Compound Index?
Intermediate

A 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
A 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 compound index matters (Prefix rule).
Mongo Shell / Code
db.users.createIndex({ "lastName": 1, "firstName": 1 });
Intermediate
45
What is a Partial Index?
Intermediate

Partial 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
Partial indexes only index documents in a collection that meet a specified filter expression. This reduces the index size and performance overhead for index updates.
Mongo Shell / Code
db.users.createIndex(
  { "email": 1 }, 
  { partialFilterExpression: { "age": { $gt: 18 } } }
);
Intermediate
46
How do you view index usage in MongoDB?
Intermediate

You can use the `.explain("executionStats")` method to see if an index was used for a particular query.

Comprehensive Solution
You can use the `.explain("executionStats")` method to see if an index was used for a particular query.
Mongo Shell / Code
db.users.find({ email: "test@test.com" }).explain("executionStats");
Intermediate
47
What is the 'oplog' (Operations Log)?
Intermediate

The 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
The 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 the oplog to keep their data in sync with the Primary.
Intermediate
48
What is an Arbiter in a Replica Set?
Intermediate

An 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
An 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 break ties. It takes very few resources.
Intermediate
49
How to backup and restore MongoDB databases?
Intermediate

Common tools are `mongodump` (binary backup) and `mongoexport` (CSV/JSON backup). Use `mongorestore` and `mongoimport` to restore.

Comprehensive Solution
Common tools are `mongodump` (binary backup) and `mongoexport` (CSV/JSON backup). Use `mongorestore` and `mongoimport` to restore.
Mongo Shell / Code
mongodump --db=interview_db --out=/backups/
Intermediate
50
What is the use of the '$out' stage in aggregation?
Intermediate

The `$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
The `$out` stage writes the resulting documents of the aggregation pipeline to a specified collection. If the collection exists, `$out` replaces it with the results.
Mongo Shell / Code
{ $out: "agg_results" }
Intermediate
51
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
- **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 coordinate pairs on a earth-like sphere.
Advanced
52
How does MongoDB handle data consistency?
Advanced

MongoDB follows the **CAP theorem** (Consistency, Availability, Partition tolerance). By default, it is a CP system. It ensures consistency via the Primary node...

Comprehensive Solution
MongoDB follows the **CAP theorem** (Consistency, Availability, Partition tolerance). By default, it is a CP system. It ensures consistency via the Primary node, but you can tune it using Write Concerns and Read Concerns (like `readConcern: "majority"`).
Advanced
53
What is Joins in MongoDB?
Advanced

MongoDB 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
MongoDB is designed to avoid joins where possible by using embedding. However, SQL-like joins can be performed across non-sharded collections using the `$lookup` aggregation stage.
Advanced
54
Explain the Working of 'Election' in Replica Sets.
Advanced

When 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
When 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 can vote but cannot become Primary.
Advanced
55
What are Change Streams?
Advanced

Change 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
Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment.
Advanced
56
Explain the use of 'Hint' in MongoDB.
Advanced

The `.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
The `.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.
Mongo Shell / Code
db.users.find({ age: 25 }).hint({ age: 1 });
Advanced
57
What is the 'wiredTiger' storage engine?
Advanced

WiredTiger is the default storage engine for MongoDB since version 3.2. Features include document-level concurrency control, compression (Snappy, Zlib), and che...

Comprehensive Solution
WiredTiger is the default storage engine for MongoDB since version 3.2. Features include document-level concurrency control, compression (Snappy, Zlib), and checkpointing for data persistence.
Advanced
58
What are Orphaned Documents?
Advanced

In 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
In 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 if a migration fails or a move is forced. MongoDB cleans them up automatically.
Advanced
59
What is the 'Journal' in MongoDB?
Advanced

The 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
The 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 the server crashes unexpectedly.
Advanced
60
Explain the 'Working Set' concept.
Advanced

The 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
The 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 set exceeds RAM, 'page faults' occur, and performance drops as MongoDB reads from disk.
Advanced
61
What is a Sparse Index?
Advanced

A 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
A 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 have the indexed field.
Mongo Shell / Code
db.users.createIndex({ "twitter_handle": 1 }, { sparse: true });
Advanced
62
Explain 'Mongoose' in the context of MongoDB.
Advanced

Mongoose 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
Mongoose 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 validation, middleware, and query building.
Advanced
63
What is the 16MB Document Limit?
Advanced

Single 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
Single BSON documents in MongoDB are limited to 16 megabytes. This limit prevents documents from growing too large and consuming excessive RAM or bandwidth. Large files should be stored using GridFS.
Advanced
64
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
- **Vertical**: Adding more CPU, RAM, or storage to a single server. Limited by hardware capacity. - **Horizontal**: Adding more servers and distributing data across them (Sharding). Virtually unlimited scalability.
Advanced
65
What is 'Read Concern' in MongoDB?
Advanced

Read concern controls the consistency and isolation properties of the data read from the replica set or sharded cluster. Examples: `local`, `majority`, `snapsho...

Comprehensive Solution
Read concern controls the consistency and isolation properties of the data read from the replica set or sharded cluster. Examples: `local`, `majority`, `snapshot`.
Advanced
66
Explain 'Map-Reduce' in MongoDB.
Advanced

Map-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
Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. It is generally replaced by the Aggregation Pipeline, which is faster and easier to use.
Advanced
67
What are 'Views' in MongoDB?
Advanced

A 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
A 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 demand.
Mongo Shell / Code
db.createView("activeUsers", "users", [{ $match: { status: "active" } }]);
Advanced
68
What is 'Causal Consistency'?
Advanced

Causal 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
Causal consistency ensures that operations are executed in a way that respects the sequence of causal dependencies. For example, if operation A happened before operation B, all clients will see A before B.
Advanced
69
How to tune MongoDB performance?
Advanced

1. 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
1. 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 processing. 5. Optimize schema design (Embedding vs Referencing).
Advanced
70
What is 'Write Strategy' for Sharding?
Advanced

Sharding write strategies include **Hashed Sharding** (even distribution) and **Ranged Sharding** (efficient range queries). Choosing depends on application acc...

Comprehensive Solution
Sharding write strategies include **Hashed Sharding** (even distribution) and **Ranged Sharding** (efficient range queries). Choosing depends on application access patterns.
Advanced
71
Explain 'Balancing' in Sharded Clusters.
Advanced

The 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
The balancer is a background process that monitors the number of chunks on each shard. If the imbalance exceeds a threshold, the balancer migrates chunks between shards to ensure even distribution.
Advanced
72
What are 'Sessions' in MongoDB?
Advanced

Sessions provide a context for operations, enabling features like ACID transactions and causal consistency. A session tracks operations and ensures they are gro...

Comprehensive Solution
Sessions provide a context for operations, enabling features like ACID transactions and causal consistency. A session tracks operations and ensures they are grouped correctly.
Advanced
73
How to monitor MongoDB?
Advanced

Use MongoDB's `mongostat` and `mongotop` CLI tools, or cloud solutions like **MongoDB Atlas** monitoring and Cloud Manager.

Comprehensive Solution
Use MongoDB's `mongostat` and `mongotop` CLI tools, or cloud solutions like **MongoDB Atlas** monitoring and Cloud Manager.
Advanced
74
What is 'Schema Validation'?
Advanced

MongoDB allows you to define validation rules for collections (JSON Schema). This ensures that documents inserted or updated conform to a specific structure.

Comprehensive Solution
MongoDB allows you to define validation rules for collections (JSON Schema). This ensures that documents inserted or updated conform to a specific structure.
Mongo Shell / Code
db.createCollection("students", { validator: { $jsonSchema: { ... } } });
Advanced
75
Explain 'Disk Compression' in WiredTiger.
Advanced

WiredTiger provides block-level compression for collections and indexes. This reduces storage footprint significantly at the cost of some CPU usage.

Comprehensive Solution
WiredTiger provides block-level compression for collections and indexes. This reduces storage footprint significantly at the cost of some CPU usage.
Advanced
76
Scenario: How to find top 5 most expensive orders using aggregation?
Scenario

Use `$sort` followed by `$limit`.

Comprehensive Solution
Use `$sort` followed by `$limit`.
Mongo Shell / Code
db.orders.aggregate([
  { $sort: { totalAmount: -1 } },
  { $limit: 5 }
]);
Scenario
77
Scenario: How to calculate total revenue per category?
Scenario

Use the `$group` stage with the `$sum` accumulator.

Comprehensive Solution
Use the `$group` stage with the `$sum` accumulator.
Mongo Shell / Code
db.sales.aggregate([
  { $group: { _id: "$category", revenue: { $sum: "$price" } } }
]);
Scenario
78
Scenario: How to find users who have exactly 3 tags?
Scenario

Use the `$size` operator in the query.

Comprehensive Solution
Use the `$size` operator in the query.
Mongo Shell / Code
db.users.find({ tags: { $size: 3 } });
Scenario
79
Scenario: How to remove a field from all documents in a collection?
Scenario

Use `updateMany()` with the `$unset` operator.

Comprehensive Solution
Use `updateMany()` with the `$unset` operator.
Mongo Shell / Code
db.users.updateMany({}, { $unset: { oldField: "" } });
Scenario
80
Scenario: How to find documents where an array field contains a specific value?
Scenario

You can query the array field directly; MongoDB will match if any element in the array matches.

Comprehensive Solution
You can query the array field directly; MongoDB will match if any element in the array matches.
Mongo Shell / Code
db.posts.find({ tags: "mongodb" });
Scenario
81
Scenario: How to perform a 'Full Text Search' for the word 'database'?
Scenario

First, create a `text` index on the field(s), then use the `$text` operator.

Comprehensive Solution
First, create a `text` index on the field(s), then use the `$text` operator.
Mongo Shell / Code
db.articles.createIndex({ content: "text" });
db.articles.find({ $text: { $search: "database" } });
Scenario
82
Scenario: How to find documents with a field that is NOT null and exists?
Scenario

Use `$ne: null` and `$exists: true`.

Comprehensive Solution
Use `$ne: null` and `$exists: true`.
Mongo Shell / Code
db.users.find({ email: { $ne: null, $exists: true } });
Scenario
83
Scenario: How to increment a counter field by 1?
Scenario

Use the `$inc` operator in an update operation.

Comprehensive Solution
Use the `$inc` operator in an update operation.
Mongo Shell / Code
db.stats.updateOne({ _id: 1 }, { $inc: { views: 1 } });
Scenario
84
Scenario: How to find documents where field A is greater than field B?
Scenario

Use the `$expr` operator to use aggregation expressions within a regular query.

Comprehensive Solution
Use the `$expr` operator to use aggregation expressions within a regular query.
Mongo Shell / Code
db.products.find({ $expr: { $gt: [ "$price", "$cost" ] } });
Scenario
85
Scenario: How to rename a field across all documents?
Scenario

Use `updateMany()` with the `$rename` operator.

Comprehensive Solution
Use `updateMany()` with the `$rename` operator.
Mongo Shell / Code
db.users.updateMany({}, { $rename: { "oldName": "newName" } });
Scenario
86
Scenario: How to push an item to an array only if it doesn't already exist?
Scenario

Use the `$addToSet` operator.

Comprehensive Solution
Use the `$addToSet` operator.
Mongo Shell / Code
db.users.updateOne({ _id: 1 }, { $addToSet: { tags: "new_tag" } });
Scenario
87
Scenario: How to get the current date in an aggregation pipeline?
Scenario

Use the `$$NOW` system variable.

Comprehensive Solution
Use the `$$NOW` system variable.
Mongo Shell / Code
db.logs.aggregate([
  { $addFields: { processedAt: "$$NOW" } }
]);
Scenario
88
Scenario: How to find documents that were created in the last 24 hours?
Scenario

Calculate the timestamp and use `$gte`.

Comprehensive Solution
Calculate the timestamp and use `$gte`.
Mongo Shell / Code
const yesterday = new Date(Date.now() - 24*60*60*1000);
db.logs.find({ createdAt: { $gte: yesterday } });
Scenario
89
Scenario: How to 'Join' users with their posts using aggregation?
Scenario

Use the `$lookup` stage.

Comprehensive Solution
Use the `$lookup` stage.
Mongo Shell / Code
db.users.aggregate([
  {
    $lookup: {
      from: "posts",
      localField: "_id",
      foreignField: "author_id",
      as: "user_posts"
    }
  }
]);
Scenario
90
Scenario: How to filter a 'joined' array from $lookup?
Scenario

Use the complex `$lookup` syntax (pipeline) or a subsequent `$filter` stage.

Comprehensive Solution
Use the complex `$lookup` syntax (pipeline) or a subsequent `$filter` stage.
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
91
Scenario: How to flatten an array of objects into separate documents?
Scenario

Use the `$unwind` stage.

Comprehensive Solution
Use the `$unwind` stage.
Mongo Shell / Code
db.orders.aggregate([{ $unwind: "$items" }]);
Scenario
92
Scenario: How to find the average age of users per city, but only for cities with more than 10 users?
Scenario

Group, then use `$match` (equivalent to SQL HAVING).

Comprehensive Solution
Group, then use `$match` (equivalent to SQL HAVING).
Mongo Shell / Code
db.users.aggregate([
  { $group: { _id: "$city", avgAge: { $avg: "$age" }, count: { $sum: 1 } } },
  { $match: { count: { $gt: 10 } } }
]);
Scenario
93
Scenario: How to update multiple fields in a single document based on conditions?
Scenario

Use an aggregation-based update (available in MongoDB 4.2+).

Comprehensive Solution
Use an aggregation-based update (available in MongoDB 4.2+).
Mongo Shell / Code
db.users.updateOne(
  { _id: 1 },
  [{ $set: { status: { $cond: { if: { $gt: ["$score", 50] }, then: "pass", else: "fail" } } } }]
);
Scenario
94
Scenario: How to pull (remove) all occurrences of 'error' from an array?
Scenario

Use the `$pull` operator.

Comprehensive Solution
Use the `$pull` operator.
Mongo Shell / Code
db.logs.updateMany({}, { $pull: { tags: "error" } });
Scenario
95
Scenario: How to find documents where a field is of a specific type (e.g., String)?
Scenario

Use the `$type` operator.

Comprehensive Solution
Use the `$type` operator.
Mongo Shell / Code
db.users.find({ age: { $type: "string" } }); // Oops, age is string here
Scenario
96
Scenario: How to perform a 'Dry Run' of a deletion?
Scenario

Run the same query with `find()` first to see which documents will be affected.

Comprehensive Solution
Run the same query with `find()` first to see which documents will be affected.
Mongo Shell / Code
db.users.find({ inactive: true }).map(u => u._id); // Preview IDs
Scenario
97
Scenario: How to get the last 10 log entries?
Scenario

Sort by `_id` or timestamp descending and limit to 10.

Comprehensive Solution
Sort by `_id` or timestamp descending and limit to 10.
Mongo Shell / Code
db.logs.find().sort({ _id: -1 }).limit(10);
Scenario
98
Scenario: How to search for coordinates within a 5km radius of a point?
Scenario

Use the `$near` operator with `$maxDistance` (in meters).

Comprehensive Solution
Use the `$near` operator with `$maxDistance` (in meters).
Mongo Shell / Code
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [ -73.96, 40.78 ] },
      $maxDistance: 5000
    }
  }
});
Scenario
99
Scenario: You need a schema where one document contains 'many' others, potentially causing size issues. Solution?
Scenario

Move 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
Move 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.
Scenario
100
How to export a collection to a JSON file?
Scenario

Use the `mongoexport` command-line utility.

Comprehensive Solution
Use the `mongoexport` command-line utility.
Mongo Shell / Code
mongoexport --db=interview_db --collection=users --out=users.json
Scenario
High-Scale Updates

Master Modern NoSQL!

Get monthly deep-dives into MongoDB architecture patterns, performance indexing, and real-world aggregation scenarios. Shared by industry experts.