MongoDB is one of the most popular NoSQL databases, known for its flexibility, scalability, and ease of use for developers. Whether you’re a beginner or an experienced developer, mastering MongoDB is essential to building modern applications that require rapid access and manipulation of data. If you’re preparing for a MongoDB interview, having a solid understanding of its core concepts is critical. In this blog post, we’ll walk through some key MongoDB interview questions that will help you stand out in your next interview.
1. What is MongoDB, and how does it differ from relational databases?
Answer: MongoDB is a NoSQL database that stores data in flexible, JSON-like documents instead of tables with rows and columns as in relational databases. It is designed to handle unstructured or semi-structured data. Differences include:
-
Schema-less: MongoDB allows dynamic schema design, whereas relational databases require a predefined schema.
-
Data storage: MongoDB stores data in BSON (Binary JSON), while relational databases use tables.
-
Scalability: MongoDB is horizontally scalable (sharding), whereas relational databases are typically vertically scalable.
-
Joins: Relational databases support joins natively, but MongoDB requires embedding or referencing documents for related data.
2. Explain the concept of sharding in MongoDB.
Answer: Sharding is the process of distributing data across multiple machines in MongoDB to ensure horizontal scaling. A shard is a single database instance that holds part of the data. MongoDB automatically distributes data across shards based on a shard key. This helps improve performance and storage capacity for large datasets.
3. What is a replica set in MongoDB?
Answer: A replica set is a group of MongoDB instances that maintain the same data, providing redundancy and high availability. It consists of:
-
Primary: Handles all write operations.
-
Secondaries: Replicate the primary’s data and can serve read operations if needed.
-
Arbiter: A lightweight member used to break ties in elections, but it doesn't store data.
4. How does MongoDB handle transactions?
Answer: MongoDB supports multi-document ACID transactions since version 4.0. This ensures that operations across multiple documents are committed or rolled back as a single unit of work, similar to relational databases. Transactions are used when consistency across multiple collections or documents is required.
5. What is the difference between find() and aggregate() in MongoDB?
Answer:
-
find()is used to perform simple queries to retrieve data from collections. It returns documents that match a query filter. -
aggregate()is more powerful and is used for complex data processing and analysis. It processes data through a pipeline of stages (e.g., filtering, grouping, sorting, etc.) to transform the data.
6. Explain the structure of a MongoDB document.
Answer: MongoDB documents are structured in BSON format (Binary JSON), and a typical document looks like a JSON object:
{
"_id": ObjectId("605c72cfe4b0f6e12e4e5b5b"),
"name": "John Doe",
"age": 29,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "traveling", "swimming"]
}
Documents can have nested objects and arrays, and each document can have different fields (schema flexibility).
7. What is indexing in MongoDB, and why is it important?
Answer: Indexing in MongoDB is the process of creating a special data structure to store a small portion of the dataset for fast querying. Indexes are crucial for improving the performance of read operations. Without an index, MongoDB performs a full collection scan to find matching documents. Common types of indexes:
-
Single-field index: Indexes a single field.
-
Compound index: Indexes multiple fields in a specific order.
-
Multikey index: Indexes arrays.
-
Text index: For full-text search.
8. How does MongoDB ensure consistency?
Answer: MongoDB ensures consistency using:
-
Replica sets: It maintains multiple copies of data across nodes, ensuring redundancy.
-
Write concern: MongoDB allows developers to specify the level of acknowledgment required for write operations (e.g., waiting for acknowledgment from the primary or all replica set members).
-
Read concern: It defines how consistent the data returned from queries is (e.g., "local," "majority").
9. How do you perform pagination in MongoDB?
Answer:
MongoDB supports pagination using the skip() and limit() methods. For example:
db.collection.find().skip(20).limit(10);
This retrieves 10 documents starting from the 21st document. However, using these for large datasets can be inefficient, and alternatives like range-based pagination (using _id) are preferred for performance.
10. What is the use of the $lookup operator in MongoDB?
Answer:
The $lookup operator is used to perform a left outer join between two collections in MongoDB. It allows you to join documents from a "foreign" collection based on matching values. Example:
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
]);
This will join the orders collection with the customers collection and store the result in the customerDetails field.
11. What is the capped collection in MongoDB?
Answer: A capped collection in MongoDB is a fixed-size collection that automatically overwrites the oldest entries when it reaches its size limit. Capped collections maintain the insertion order and are ideal for use cases like logs where the latest data is of primary importance.
12. How do you optimize queries in MongoDB?
Answer: To optimize MongoDB queries, developers can:
-
Use indexes: Ensure appropriate indexes are in place for frequently queried fields.
-
Avoid large documents: Keep documents small and avoid deeply nested arrays/objects.
-
Use projection: Only return the necessary fields using the projection parameter.
-
Profile queries: Use MongoDB’s profiler to identify slow queries.
-
Avoid
$wherequeries: They are slow since they execute JavaScript.
13. What is the aggregation framework in MongoDB?
Answer: The aggregation framework is a powerful tool in MongoDB for data transformation and analysis. It processes data through a pipeline where each stage transforms the data. Common stages include:
-
$match: Filters documents.
-
$group: Groups documents by a specific field.
-
$sort: Sorts documents.
-
$project: Reshapes the output by adding/removing fields.
14. Explain the difference between MongoDB and Mongoose.
Answer:
-
MongoDB: It is the NoSQL database itself.
-
Mongoose: It is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model your application data, making it easier to enforce structure on MongoDB’s flexible documents.
15. What are some common use cases for MongoDB?
Answer: MongoDB is commonly used in:
-
Real-time analytics (e.g., social media, IoT).
-
Content management systems (CMS).
-
E-commerce platforms (handling product catalogs).
-
Big data applications.
-
Geospatial data storage (location-based apps).
16. How do you update multiple documents in MongoDB?
Answer:
To update multiple documents in MongoDB, you can use the updateMany() method. This method allows you to update all the documents that match a query.
Example:
Suppose you want to update the status of all orders that are still pending:
db.orders.updateMany(
{ status: "pending" }, // Query to find all pending orders
{ $set: { status: "shipped" } } // Update to set the status to 'shipped'
);
This will update the status field of all matching documents to "shipped."
17. What is the difference between $set and $unset operators?
Answer:
-
$set: Used to add or update a field in a document. -
$unset: Used to remove a field from a document.
Example:
-
$setExample: Add or update the "age" field in theuserscollection.
db.users.updateOne(
{ name: "John" },
{ $set: { age: 30 } }
);
-
$unsetExample: Remove the "address" field from all user documents:
db.users.updateMany(
{}, // No condition, affects all documents
{ $unset: { address: "" } }
);
18. How do you perform text search in MongoDB?
Answer:
MongoDB provides full-text search capabilities through the text index and the $text query operator.
Example:
Suppose you have a blogs collection with a content field. You want to find documents that contain the word "MongoDB":
db.blogs.createIndex({ content: "text" }); // Create text index on the 'content' field
db.blogs.find({ $text: { $search: "MongoDB" } });
This query will return all documents where the content field contains the word "MongoDB."
19. Explain the $push operator in MongoDB with an example.
Answer:
The $push operator is used to append a value to an array field in a document.
Example:
Suppose you have a students collection, and you want to add a new grade to a student's grades array:
db.students.updateOne(
{ name: "Alice" },
{ $push: { grades: 85 } }
);
This will append the grade 85 to the grades array of the student named "Alice."
20. How do you delete documents in MongoDB?
Answer: MongoDB provides two methods for deleting documents:
-
deleteOne(): Deletes a single document that matches the filter. -
deleteMany(): Deletes multiple documents that match the filter.
Example:
-
Deleting a single document:
db.users.deleteOne({ name: "John" });
This deletes the first document where the name is "John."
-
Deleting multiple documents:
db.users.deleteMany({ age: { $lt: 18 } });
This deletes all documents where the age field is less than 18.
21. What is $regex in MongoDB, and how is it used for pattern matching?
Answer:
The $regex operator is used to perform pattern matching with regular expressions in MongoDB.
Example: Suppose you want to find all users whose names start with the letter "A":
db.users.find({ name: { $regex: "^A" } });
This query will return all users whose names start with "A" (case-sensitive). To make it case-insensitive, you can add the i flag:
db.users.find({ name: { $regex: "^A", $options: "i" } });
22. What are MongoDB projections, and how are they used?
Answer: Projections in MongoDB are used to control which fields are returned by a query. You can include or exclude specific fields using a projection.
Example:
Suppose you want to fetch the names and ages of all users but exclude their _id field:
db.users.find(
{}, // No filter, select all documents
{ name: 1, age: 1, _id: 0 } // Project only 'name' and 'age' fields, exclude '_id'
);
This query will return documents with only the name and age fields.
23. What are embedded documents in MongoDB?
Answer: MongoDB allows you to embed documents within other documents to represent relationships. This approach is useful for storing related data together in a single document, avoiding the need for complex joins.
Example:
Suppose you have a users collection, and you want to store an embedded address object within each user document:
db.users.insertOne({
name: "Jane",
age: 28,
address: {
street: "123 Main St",
city: "New York",
zip: "10001"
}
});
In this case, address is an embedded document inside the user document.
24. Explain $in and $nin operators in MongoDB with examples.
Answer:
-
$in: Matches values in an array of possible values. -
$nin: Matches values that are not in an array of possible values.
Example:
-
Using
$in:
db.users.find({ age: { $in: [25, 30, 35] } });
This query will return all users whose age is either 25, 30, or 35.
-
Using
$nin:
db.users.find({ age: { $nin: [18, 19, 20] } });
This query will return all users whose age is not 18, 19, or 20.
25. How do you sort results in MongoDB?
Answer:
MongoDB provides the sort() method to sort the result set based on one or more fields. Sorting can be done in ascending (1) or descending (-1) order.
Example: Sort users by age in descending order:
db.users.find().sort({ age: -1 });
This query will return all users sorted by age in descending order.
26. What is the $group stage in the aggregation framework?
Answer:
The $group stage is used in the MongoDB aggregation pipeline to group documents by a specified field and perform aggregation operations (like summing or averaging) on grouped data.
Example:
Suppose you have a sales collection, and you want to group sales data by the product field and calculate the total sales for each product:
db.sales.aggregate([
{
$group: {
_id: "$product", // Group by 'product' field
totalSales: { $sum: "$amount" } // Sum the 'amount' field for each group
}
}
]);
This will return the total sales amount for each product.
27. What are compound indexes in MongoDB?
Answer: Compound indexes in MongoDB are indexes that include more than one field. They are used to optimize queries that involve multiple fields.
Example:
Suppose you frequently query the users collection by both age and name. You can create a compound index to optimize these queries:
db.users.createIndex({ age: 1, name: 1 });
This will create an index that sorts first by age (ascending) and then by name (ascending).
28. What is ObjectId in MongoDB, and how is it structured?
Answer:
ObjectId is the default primary key in MongoDB and serves as the unique identifier for each document. It is a 12-byte value consisting of:
-
4 bytes representing the timestamp of creation.
-
5 bytes representing a random value.
-
3 bytes representing an incrementing counter.
Example:
{ _id: ObjectId("605c72cfe4b0f6e12e4e5b5b") }
29. What is the $lookup stage in MongoDB's aggregation pipeline?
Answer:
The $lookup stage in the aggregation pipeline is used to perform joins between two collections. It allows you to join data from one collection into another similar to a SQL JOIN.
Example:
Suppose you have two collections: orders and customers, and you want to join them on the customer_id field.
db.orders.aggregate([
{
$lookup: {
from: "customers", // The collection to join
localField: "customer_id", // Field from the 'orders' collection
foreignField: "_id", // Field from the 'customers' collection
as: "customerDetails" // Output array field name for matched data
}
}
]);
This query joins data from the customers collection with the orders collection based on matching customer_id.
30. Explain sharding in MongoDB and how it works.
Answer: Sharding is MongoDB’s method of distributing data across multiple servers to ensure horizontal scaling and high availability for large datasets. MongoDB shards data by splitting it across multiple machines (shards) based on a shard key. Each shard is responsible for storing a portion of the dataset.
-
Shard Key: A field used to determine how data is distributed across the shards.
-
Config Server: Keeps metadata and configuration settings for the cluster.
-
Query Router (Mongos): Routes client queries to the appropriate shards.
Example:
sh.enableSharding("myDatabase"); // Enable sharding on a database
sh.shardCollection("myDatabase.myCollection", { userId: 1 }); // Shard by 'userId' field
This enables sharding for myCollection using the userId field as the shard key.
31. What is the $expr operator, and how is it used in queries?
Answer:
The $expr operator allows you to use aggregation expressions within a query, enabling you to compare fields within the same document.
Example:
Find all products where the quantity field is greater than the minimum_quantity field:
db.products.find({ $expr: { $gt: ["$quantity", "$minimum_quantity"] }
});
This query compares the quantity and minimum_quantity fields for each document and returns documents where quantity is greater.
32. Explain the purpose of capped collections in MongoDB.
Answer: Capped collections are fixed-size collections in MongoDB that automatically overwrite the oldest documents when they reach their size limit. These collections are useful for use cases where you need a rolling history, such as logging.
-
Key Features:
-
Fixed size.
-
Data is written in a circular fashion.
-
Data is ordered in insertion order.
-
Example: Create a capped collection with a size of 1MB and a maximum of 1000 documents:
db.createCollection("logs", { capped: true, size: 1048576, max: 1000 });
This creates a capped collection where the total size of all documents is 1MB, and it can store up to 1000 documents.
33. What are replica sets in MongoDB?
Answer: A replica set in MongoDB is a group of MongoDB servers that maintain the same data set, providing redundancy and high availability. Replica sets allow automatic failover and data replication.
-
Primary: Handles all write operations.
-
Secondary: Replicates data from the primary. Can serve read queries if configured.
-
Arbiter: Participates in elections but doesn't store data.
Example:
rs.initiate({
_id: "myReplicaSet",
members: [
{ _id: 0, host: "server1:27017" },
{ _id: 1, host: "server2:27017" },
{ _id: 2, host: "server3:27017" }
]
});
This initializes a replica set with three members (server1, server2, server3).
34. How do you manage relationships between collections in MongoDB?
Answer: There are two main ways to manage relationships in MongoDB:
-
Embedded Documents (Denormalization): This approach embeds one document inside another, making queries faster but potentially increasing document size.
Example:
db.users.insertOne({ name: "John", address: { street: "123 Main St", city: "New York" } }); -
Reference Documents (Normalization): Store references (foreign keys) to documents in other collections.
Example:
db.orders.insertOne({ orderId: 123, customerId: ObjectId("605c72cfe4b0f6e12e4e5b5b") // Reference to a document in 'customers' });
35. What is $merge in MongoDB aggregation?
Answer:
The $merge stage in the aggregation pipeline is used to output the results of the aggregation pipeline into another collection or to update existing documents in the same collection.
Example:
Suppose you want to aggregate sales data and merge the results into a totalSales collection:
db.sales.aggregate([
{ $group: { _id: "$product", total: { $sum: "$amount" } } },
{ $merge: "totalSales" }
]);
This aggregation groups sales by product and merges the result into the totalSales collection.
36. Explain the $out operator in MongoDB.
Answer:
The $out stage in the aggregation pipeline writes the result of the aggregation directly to a new collection. It replaces the content of the collection, unlike $merge which updates documents.
Example: You can aggregate the data from one collection and output it to another:
db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } },
{ $out: "customerTotals" }
]);
This will aggregate the total amount spent by each customer on "shipped" orders and store the result in the customerTotals collection.
37. What are geospatial queries in MongoDB, and how are they performed?
Answer:
MongoDB provides geospatial indexing and querying to store and query geographical data (e.g., latitude/longitude). You can use operators like $near, $geoWithin, and $geoIntersects to query geospatial data.
Example: Find all stores within 10km of a given point:
db.stores.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [77.5946, 12.9716] }, // Bangalore coords
$maxDistance: 10000 // Distance in meters
}
}
});
This query finds all stores within 10 kilometers of a specific coordinate.
38. How does MongoDB handle large datasets using GridFS?
Answer:
GridFS is MongoDB's specification for storing and retrieving large files (such as images, videos, and audio) that exceed the BSON-document size limit (16 MB). GridFS splits large files into smaller chunks and stores them in two collections: fs.files and fs.chunks.
Example:
To store a large file in GridFS, you can use MongoDB drivers or tools like mongofiles:
mongofiles -d myDatabase put largeFile.txt
This will split the file largeFile.txt into chunks and store it in the myDatabase database.
39. What is the aggregation pipeline in MongoDB, and how does it work?
Answer: The aggregation pipeline is a powerful framework for data aggregation in MongoDB. It allows you to process data in stages, where each stage performs an operation on the input and passes the result to the next stage.
-
Key stages:
-
$match: Filters documents by a condition. -
$group: Groups documents by a field and performs aggregation operations. -
$sort: Sorts documents by a specified field. -
$project: Reshapes the document by including/excluding fields.
-
Example: Calculate the total sales per product:
db.sales.aggregate([
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } },
{ $sort: { totalSales: -1 } } // Sort by total sales in descending order
]);
40. What is the difference between a database transaction in MongoDB and a session?
Answer: A transaction in MongoDB ensures multiple write operations (across multiple documents) are atomic, meaning they either all succeed or all fail. Transactions are typically used in replica sets and sharded clusters.
A session provides a way to group multiple operations in MongoDB, and can be used to start a transaction or execute multiple commands with consistent read/write behavior.
const session = db.getMongo().startSession();
session.startTransaction();
try {
db.customers.updateOne({ _id: customerId }, { $inc: { balance: -100 } }, { session });
db.orders.insertOne({ orderId: 1, total: 100 }, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction();
} finally {
session.endSession();
}
In this example, both the updateOne and insertOne operations are part of a transaction, ensuring atomicity.
41. What is the difference between save() and insert() in MongoDB?
Answer:
Both save() and insert() are used to add documents to a MongoDB collection, but they behave differently:
-
insert(): Inserts new documents. If the document contains an_idthat already exists, it will throw a duplicate key error. -
save(): If the document contains an_idfield, it will update the existing document with that_id(if found); otherwise, it will insert the document as a new one. In this way, it can behave like bothinsert()andupdate().
Example:
// Using insert()
db.customers.insert({ _id: 1, name: "John" }); // Throws error if _id already exists
// Using save()
db.customers.save({ _id: 1, name: "John" }); // Updates if _id exists, inserts otherwise
42. Explain how MongoDB handles atomicity and isolation in operations.
Answer: MongoDB provides atomicity at the document level. All write operations that modify a single document (e.g., inserts, updates, deletes) are atomic. This ensures that no partial updates or reads of an incomplete document occur.
For multi-document transactions, MongoDB uses ACID-compliant transactions starting from version 4.0, allowing multiple operations across multiple documents to be executed atomically.
Example: Single-document atomicity:
db.accounts.update(
{ _id: 123 },
{ $inc: { balance: -50 } } // Atomic operation
);
Multi-document transaction:
const session = db.getMongo().startSession();
session.startTransaction();
try {
db.accounts.update({ _id: 123 }, { $inc: { balance: -100 } }, { session });
db.accounts.update({ _id: 456 }, { $inc: { balance: 100 } }, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction(); // Roll back changes
} finally {
session.endSession();
}
43. How does MongoDB implement read preferences, and what are the different modes?
Answer: MongoDB allows clients to specify read preferences to control from which members of a replica set they should read data. This is useful for distributing read traffic and handling eventual consistency.
-
Primary: Reads from the primary (default).
-
PrimaryPreferred: Reads from the primary if available, otherwise from a secondary.
-
Secondary: Reads from a secondary.
-
SecondaryPreferred: Reads from a secondary if available, otherwise from the primary.
-
Nearest: Reads from the nearest node in terms of network latency, regardless of primary or secondary.
Example:
db.collection.find({}, { readPreference: "secondary" });
This query reads data from a secondary member of the replica set.
44. Explain how MongoDB handles indexes and how to create compound indexes.
Answer: MongoDB uses indexes to improve the performance of queries. An index is a data structure that holds field values in a specific order, making it faster to locate documents based on queries.
A compound index indexes multiple fields, which is helpful when queries need to filter or sort by more than one field.
Example:
Create a compound index on firstName and lastName fields:
db.customers.createIndex({ firstName: 1, lastName: 1 });
This index will help optimize queries that sort or filter by both firstName and lastName.
45. What is a partial index in MongoDB?
Answer: A partial index only indexes documents that meet a specific condition. This can save space and improve query performance by focusing on a subset of the data.
Example:
Create an index on the status field, but only for documents where status is "active":
db.users.createIndex(
{ status: 1 },
{ partialFilterExpression: { status: "active" } }
);
This will only index documents with status: "active", improving performance for queries targeting active users.
46. What is a text index in MongoDB, and how can it be used for full-text search?
Answer: MongoDB supports text indexes to enable full-text search on string fields. Text indexes are useful when you need to search text-based content in your collections.
Example:
Create a text index on the description field:
db.products.createIndex({ description: "text" });
Now, you can perform full-text search queries like:
db.products.find({ $text: { $search: "laptop" } });
You can also rank results by their text score:
db.products.find({ $text: { $search: "laptop" } }, { score: { $meta: "textScore" } })
.sort({ score: { $meta: "textScore" } });
47. Explain the use of $facet in MongoDB aggregation.
Answer:
The $facet stage in the aggregation pipeline allows you to perform multiple aggregations on the same set of documents within a single query. Each facet performs an independent aggregation, and the results are combined into a single output.
Example:
db.sales.aggregate([
{
$facet: {
totalSales: [{ $group: { _id: null, total: { $sum: "$amount" } } }],
byProduct: [{ $group: { _id: "$product", total: { $sum: "$amount" } } }]
}
}
]);
This aggregation computes the total sales and sales by product in parallel.
48. What is the $cond operator in MongoDB?
Answer:
The $cond operator allows you to use if-then-else logic in aggregation pipelines. It evaluates a condition and returns one of two expressions based on whether the condition is true or false.
Example:
db.orders.aggregate([
{
$project: {
status: 1,
discount: {
$cond: {
if: { $eq: ["$status", "VIP"] },
then: 20,
else: 5
}
}
}
}
]);
This query applies a discount of 20% for VIP customers and 5% for others.
49. What is MongoDB's $unwind operator and how is it used?
Answer:
The $unwind operator is used to deconstruct an array field in documents, creating a separate document for each element of the array. This is useful when you need to treat array elements as individual documents.
Example:
Suppose you have a products collection where each document has an array of tags:
db.products.aggregate([
{ $unwind: "$tags" }
]);
If a product has multiple tags, $unwind will output one document per tag, allowing further processing on individual tags.
50. Explain $redact in MongoDB aggregation.
Answer:
The $redact stage allows you to filter parts of documents based on access control or conditions. It traverses documents and applies access control rules at both the document and sub-document levels.
-
$$DESCEND: Keep the current document and continue evaluating sub-documents. -
$$PRUNE: Remove the current document. -
$$KEEP: Keep the current document as it is.
Example:
Filter out any fields marked as private:
db.profiles.aggregate([
{
$redact: {
$cond: {
if: { $eq: ["$private", true] },
then: "$$PRUNE",
else: "$$DESCEND"
}
}
}
]);
This removes documents or sub-documents marked as private.
51. What is the difference between $project and $addFields in MongoDB aggregation?
Answer:
-
$project: Used to include or exclude fields from the document. It can also be used to reshape documents by renaming fields or computing new fields. -
$addFields: Adds new fields to documents without removing existing fields. It is similar to$project, but it adds fields rather than replacing them.
Example:
Using $project:
db.customers.aggregate([
{ $project: { name: 1, balance: 1, discount: { $multiply: ["$balance", 0.1] } } }
]);
Using $addFields:
db.customers.aggregate([
{ $addFields: { discount: { $multiply: ["$balance", 0.1] } } }
]);
52. How does MongoDB perform horizontal scaling?
Answer: MongoDB achieves horizontal scaling through sharding. It partitions data across multiple servers (shards), allowing data to be distributed and queried in parallel. Sharding helps to scale out large datasets by balancing data across multiple nodes.
-
Sharded Cluster Components:
-
Shard: Stores part of the data.
-
Config Servers: Store metadata about the sharded cluster.
-
Mongos Router: Routes queries to the appropriate shard.
-
-
Sharding Key: The field used to determine how data is distributed across shards. A well-chosen sharding key is critical for balanced distribution.
Example: Enable sharding for a database:
sh.enableSharding("myDatabase");
Create a sharded collection:
sh.shardCollection("myDatabase.customers", { customerId: 1 });
These questions and examples should help you further prepare for advanced MongoDB interviews, focusing on real-world scenarios and problem-solving skills.