100+ MongoDB Interview Questions with Examples and Explanations for Developers

    Here’s a list of 100 commonly asked MongoDB interview questions, along with answers and examples. The questions cover various aspects of MongoDB, including its features, operations, and use cases.

    1. What is MongoDB?

    Answer:

    MongoDB is a NoSQL document-oriented database that stores data in JSON-like documents. It provides high performance, high availability, and easy scalability.

    Example:

    A user profile can be stored as a document:

    {
      "name": "John Doe",
      "email": "john@example.com",
      "age": 30
    }
    

    2. What are the main features of MongoDB?

    Answer:

    • Document-oriented: Data is stored in documents (BSON format).
    • Schema-less: No predefined schema, allowing flexibility.
    • Scalability: Supports horizontal scaling through sharding.
    • High Availability: Replica sets provide redundancy.
    • Indexing: Supports various types of indexes to improve query performance.

    3. What is BSON?

    Answer:

    BSON (Binary JSON) is the binary representation of JSON-like documents in MongoDB. It supports more data types than JSON, such as date and binary data.

    4. What is a collection in MongoDB?

    Answer:

    A collection is a grouping of MongoDB documents. It is equivalent to a table in relational databases but does not enforce a schema.

    Example:

    A collection named users can store user profile documents.

    5. What is a database in MongoDB?

    Answer:

    A database in MongoDB is a container for collections. Each database can contain multiple collections and operates independently.

    6. How do you create a database in MongoDB?

    Answer:

    A database is created by using the use command. If the database does not exist, it will be created when you insert data into it.

    Example:

    use myDatabase
    

    7. How do you insert a document into a collection?

    Answer:

    You can use the insertOne or insertMany method to add documents to a collection.

    Example:

    db.users.insertOne({ name: "Alice", age: 25 });
    

    8. How do you retrieve documents from a collection?

    Answer:

    You can use the find method to retrieve documents.

    Example:

    db.users.find({ age: { $gt: 20 } });
    

    9. What are queries in MongoDB?

    Answer:

    Queries in MongoDB are used to filter and retrieve documents from collections based on specified criteria.

    10. How do you update a document in MongoDB?

    Answer:

    You can use the updateOne, updateMany, or replaceOne methods to update documents.

    Example:

    db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } });
    

    11. How do you delete a document in MongoDB?

    Answer:

    You can use the deleteOne or deleteMany method to remove documents from a collection.

    Example:

    db.users.deleteOne({ name: "Alice" });
    

    12. What is an index in MongoDB?

    Answer:

    An index is a data structure that improves the speed of data retrieval operations on a collection. MongoDB supports various types of indexes.

    13. How do you create an index in MongoDB?

    Answer:

    You can use the createIndex method to create an index on a collection.

    Example:

    db.users.createIndex({ email: 1 });
    

    14. What is a replica set in MongoDB?

    Answer:

    A replica set is a group of MongoDB servers that maintain the same dataset, providing redundancy and high availability. It consists of a primary node and multiple secondary nodes.

    15. What is sharding in MongoDB?

    Answer:

    Sharding is a method of horizontal scaling that distributes data across multiple servers to handle large datasets and high throughput operations.

    16. What is a primary node in a replica set?

    Answer:

    The primary node is the main node in a replica set that receives all write operations. It replicates its data to secondary nodes.

    17. What is a secondary node in a replica set?

    Answer:

    Secondary nodes replicate data from the primary node and can serve read operations. They provide redundancy and high availability.

    18. What is the purpose of the findOne method?

    Answer:

    The findOne method retrieves a single document from a collection that matches the specified query criteria.

    Example:

    db.users.findOne({ name: "Alice" });
    

    19. How do you count documents in a collection?

    Answer:

    You can use the countDocuments method to count the number of documents matching a query.

    Example:

    db.users.countDocuments({ age: { $gt: 20 } });
    

    20. What is the aggregation framework in MongoDB?

    Answer:

    The aggregation framework is a powerful tool for processing data and performing operations like filtering, grouping, and sorting.

    21. How do you perform an aggregation in MongoDB?

    Answer:

    You can use the aggregate method to perform aggregations on a collection.

    Example:

    db.users.aggregate([
      { $match: { age: { $gt: 20 } } },
      { $group: { _id: "$age", count: { $sum: 1 } } }
    ]);
    

    22. What is the difference between find and aggregate?

    Answer:

    • find: Retrieves documents directly based on query criteria.
    • aggregate: Processes data through multiple stages for more complex operations (e.g., filtering, grouping).

    23. What is a compound index?

    Answer:

    A compound index is an index on multiple fields in a document, allowing efficient querying on those fields.

    Example:

    db.users.createIndex({ age: 1, name: 1 });
    

    24. What is a wildcard index?

    Answer:

    A wildcard index is an index that can be applied to fields with dynamic names. It is useful for collections where documents may have varying structures.

    Example:

    db.collection.createIndex({ "$**": 1 });
    

    25. How do you handle errors in MongoDB?

    Answer:

    You can handle errors using try-catch blocks in your application code or by checking the error codes returned by MongoDB operations.

    26. What is a stored procedure in MongoDB?

    Answer:

    MongoDB does not support traditional stored procedures as in relational databases. However, you can use JavaScript functions defined on the server to perform similar operations.

    27. What are transactions in MongoDB?

    Answer:

    Transactions in MongoDB allow multiple operations to be executed in an all-or-nothing manner, ensuring data consistency. They are available in replica sets and sharded clusters.

    28. How do you start a transaction in MongoDB?

    Answer:

    You can start a transaction using the startSession method and then the startTransaction method.

    Example:

    const session = client.startSession();
    session.startTransaction();
    

    29. How do you commit a transaction in MongoDB?

    Answer:

    You can commit a transaction using the commitTransaction method on the session.

    Example:

    await session.commitTransaction();
    

    30. How do you abort a transaction in MongoDB?

    Answer:

    You can abort a transaction using the abortTransaction method on the session.

    Example:

    await session.abortTransaction();
    

    31. What is the purpose of the upsert option in updates?

    Answer:

    The upsert option allows you to create a new document if no documents match the query criteria during an update operation.

    Example:

    db.users.updateOne(
      { name: "Alice" },
      { $set: { age: 25 } },
      { upsert: true }
    );
    

    32. What are capped collections?

    Answer:

    Capped collections are fixed-size collections that maintain insertion order and automatically overwrite the oldest documents when the size limit is reached. They are useful for logging.

    33. How do you create a capped collection?

    Answer:

    You can create a capped collection using the create command with the capped option.

    Example:

    db.createCollection("logs", { capped: true, size: 1024 });
    

    34. What is the $match stage in aggregation?

    Answer:

    The $match stage filters documents based on specified criteria, similar to the find operation.

    Example:

    db.users.aggregate([
      { $match: { age: { $gt: 25 } } }
    ]);
    

    35. What is the $group stage in aggregation?

    Answer:

    The $group stage groups documents by specified fields and performs aggregate operations (e.g., count, sum).

    Example:

    db.users.aggregate([
      { $group: { _id: "$age", count: { $sum: 1 } } }
    ]);
    

    36. What is the $sort stage in aggregation?

    Answer:

    The $sort stage sorts the documents in the specified order based on one or more fields.

    Example:

    db.users.aggregate([
      { $sort: { age: -1 } }
    ]);
    

    37. What is the $project stage in aggregation?

    Answer:

    The $project stage reshapes documents by including, excluding, or adding new fields.

    Example:

    db.users.aggregate([
      { $project: { name: 1, age: 1, _id: 0 } }
    ]);
    

    38. What is the difference between findOneAndUpdate and updateOne?

    Answer:

    • findOneAndUpdate: Finds a single document, updates it, and returns the original or modified document.
    • updateOne: Updates a document without returning it.

    Example:

    db.users.findOneAndUpdate(
      { name: "Alice" },
      { $set: { age: 26 } },
      { returnOriginal: false }
    );
    

    39. How do you perform a text search in MongoDB?

    Answer:

    You can perform text searches using the $text operator after creating a text index on the desired fields.

    Example:

    db.users.createIndex({ name: "text", email: "text" });
    db.users.find({ $text: { $search: "Alice" } });
    

    40. What are transactions in MongoDB?

    Answer:

    Transactions in MongoDB allow you to execute multiple operations in a single atomic unit. They ensure that either all operations succeed or none at all.

    41. How do you enable sharding in MongoDB?

    Answer:

    Sharding can be enabled by configuring a sharded cluster and specifying a shard key.

    42. What is a shard key?

    Answer:

    A shard key is a field or set of fields used to distribute data across shards in a sharded cluster. It determines how data is partitioned.

    43. What is a query router (mongos)?

    Answer:

    A query router (mongos) is a service that routes client requests to the appropriate shards in a sharded MongoDB cluster.

    44. What are the different types of indexes in MongoDB?

    Answer:

    • Single Field Index: Index on a single field.
    • Compound Index: Index on multiple fields.
    • Multikey Index: Index on array fields.
    • Text Index: Index for text search.
    • Geospatial Index: Index for geospatial queries.

    45. How do you drop an index in MongoDB?

    Answer:

    You can use the dropIndex method to remove an index from a collection.

    Example:

    db.users.dropIndex("indexName");
    

    46. What is the purpose of explain() in MongoDB?

    Answer:

    The explain() method provides information about how a query is executed, including details on the query plan, indexes used, and execution time.

    Example:

    db.users.find({ age: { $gt: 25 } }).explain("executionStats");
    

    47. What is the $unset operator?

    Answer:

    The $unset operator removes a specified field from a document.

    Example:

    db.users.updateOne({ name: "Alice" }, { $unset: { age: "" } });
    

    48. What is the $push operator?

    Answer:

    The $push operator adds an element to an array field in a document.

    Example:

    db.users.updateOne({ name: "Alice" }, { $push: { hobbies: "Reading" } });
    

    49. What is the $pull operator?

    Answer:

    The $pull operator removes elements from an array field that match a specified condition.

    Example:

    db.users.updateOne({ name: "Alice" }, { $pull: { hobbies: "Reading" } });
    

    50. What is the difference between insertOne and insertMany?

    Answer:

    • insertOne: Inserts a single document into a collection.
    • insertMany: Inserts multiple documents into a collection in a single operation.

    Example:

    db.users.insertMany([{ name: "Bob" }, { name: "Charlie" }]);
    

    51. What is a unique index?

    Answer:

    A unique index ensures that the indexed field does not have duplicate values. It can be created on one or more fields.

    Example:

    db.users.createIndex({ email: 1 }, { unique: true });
    

    52. How do you handle versioning in MongoDB?

    Answer:

    Versioning can be handled by maintaining a version field in documents or using separate collections to store versions.

    53. What is the aggregate method?

    Answer:

    The aggregate method is used to process data records and return computed results. It can perform operations like filtering, grouping, and sorting.

    54. What is a change stream in MongoDB?

    Answer:

    Change streams allow applications to listen for real-time changes to documents in a collection, providing a way to react to changes as they happen.

    55. How do you create a change stream?

    Answer:

    You can create a change stream using the watch method on a collection.

    Example:

    const changeStream = db.users.watch();
    changeStream.on("change", (change) => {
      console.log(change);
    });
    

    56. What are the use cases for MongoDB?

    Answer:

    • Content management systems
    • Real-time analytics
    • Internet of Things (IoT) applications
    • Mobile applications
    • Catalogs and inventory management

    57. What is horizontal scaling?

    Answer:

    Horizontal scaling involves adding more servers or nodes to a system to handle increased load, as opposed to vertical scaling, which adds resources to existing servers.

    58. What is vertical scaling?

    Answer:

    Vertical scaling involves adding more resources (CPU, RAM) to an existing server to improve performance.

    59. What is the purpose of the limit method?

    Answer:

    The limit method restricts the number of documents returned by a query.

    Example:

    db.users.find().limit(5);
    

    60. What is the $or operator?

    Answer:

    The $or operator is used to perform a logical OR operation on an array of conditions.

    Example:

    db.users.find({ $or: [{ age: 25 }, { age: 30 }] });
    

    61. What is the $and operator?

    Answer:

    The $and operator is used to perform a logical AND operation on an array of conditions.

    Example:

    db.users.find({ $and: [{ age: { $gt: 20 } }, { name: "Alice" }] });
    

    62. What is the $in operator?

    Answer:

    The $in operator matches documents where the value of a field is equal to any value in a specified array.

    Example:

    db.users.find({ age: { $in: [25, 30, 35] } });
    

    63. What is the $exists operator?

    Answer:

    The $exists operator matches documents that contain a specified field.

    Example:

    db.users.find({ age: { $exists: true } });
    

    64. What is the $regex operator?

    Answer:

    The $regex operator matches documents with string fields that match a specified regular expression.

    Example:

    db.users.find({ name: { $regex: /^A/ } });
    

    65. What is the $lookup operator in aggregation?

    Answer:

    The $lookup operator performs a left outer join to combine documents from two collections.

    Example:

    db.orders.aggregate([
      {
        $lookup: {
          from: "users",
          localField: "userId",
          foreignField: "_id",
          as: "userDetails"
        }
      }
    ]);
    

    66. What is the purpose of the upsert option?

    Answer:

    The upsert option allows you to create a document if no document matches the query criteria during an update operation.

    Example:

    db.users.updateOne(
      { name: "Alice" },
      { $set: { age: 26 } },
      { upsert: true }
    );
    

    67. How do you retrieve the last inserted document in a collection?

    Answer:

    You can retrieve the last inserted document using the find method with sorting and limiting.

    Example:

    db.users.find().sort({ _id: -1 }).limit(1);
    

    68. What is the purpose of the skip method?

    Answer:

    The skip method is used to skip a specified number of documents in a query result.

    Example:

    db.users.find().skip(5);
    

    69. What is the purpose of the distinct method?

    Answer:

    The distinct method returns an array of distinct values for a specified field across a collection.

    Example:

    db.users.distinct("age");
    

    70. What is the collation option?

    Answer:

    The collation option allows you to specify language-specific rules for string comparison (e.g., case sensitivity).

    Example:

    db.users.find({ name: "alice" }).collation({ locale: "en", strength: 2 });
    

    71. What are embedded documents in MongoDB?

    Answer:

    Embedded documents are documents stored within other documents, allowing for complex data structures.

    Example:

    {
      name: "Alice",
      address: {
        street: "123 Main St",
        city: "New York"
      }
    }
    

    72. What are references in MongoDB?

    Answer:

    References are links between documents in different collections, allowing you to establish relationships.

    Example:

    {
      name: "Alice",
      orderId: ObjectId("60c72b2f4f1a2f001c8e4c2e")
    }
    

    73. What is the difference between a primary key and a unique key in MongoDB?

    Answer:

    • Primary Key: A unique identifier for each document in a collection, automatically indexed as _id.
    • Unique Key: A field or set of fields that must have unique values, but not automatically indexed as _id.

    74. What is the $setOnInsert operator?

    Answer:

    The $setOnInsert operator sets a field to a specified value only when a new document is being inserted.

    Example:

    db.users.updateOne(
      { name: "Alice" },
      { $set: { age: 26 }, $setOnInsert: { createdAt: new Date() } },
      { upsert: true }
    );
    

    75. What is a MongoDB replica set?

    Answer:

    A replica set is a group of MongoDB servers that maintain the same data set, providing redundancy and high availability.

    76. What is the difference between a primary and secondary member in a replica set?

    Answer:

    • Primary Member: The main server that receives all write operations.
    • Secondary Member: Replicates data from the primary and can serve read operations.

    77. What is the mongod process?

    Answer:

    The mongod process is the primary daemon that runs the MongoDB server.

    78. What is the purpose of the mongos process?

    Answer:

    The mongos process is a routing service for sharded clusters, directing client requests to the appropriate shards.

    79. What is a data model in MongoDB?

    Answer:

    A data model defines how data is structured and stored in MongoDB, which can be document-based, key-value, or graph-based.

    80. What is the purpose of the find() method?

    Answer:

    The find() method retrieves documents from a collection based on specified criteria.

    81. What is the $currentDate operator?

    Answer:

    The $currentDate operator sets a field to the current date when performing an update.

    Example:

    db.users.updateOne(
      { name: "Alice" },
      { $currentDate: { lastModified: true } }
    );
    

    82. What is the $inc operator?

    Answer:

    The $inc operator increments a field by a specified value.

    Example:

    db.users.updateOne({ name: "Alice" }, { $inc: { age: 1 } });
    

    83. What is the $addFields stage in aggregation?

    Answer:

    The $addFields stage adds new fields to documents in the aggregation pipeline.

    Example:

    db.users.aggregate([
      { $addFields: { ageInMonths: { $multiply: ["$age", 12] } } }
    ]);
    

    84. What is the $merge stage in aggregation?

    Answer:

    The $merge stage writes the results of an aggregation pipeline into a collection, allowing for updating or creating documents.

    Example:

    db.users.aggregate([
      { $group: { _id: "$age", count: { $sum: 1 } } },
      { $merge: { into: "ageCounts" } }
    ]);
    

    85. What is the $replaceRoot stage in aggregation?

    Answer:

    The $replaceRoot stage replaces a document's root with a specified document.

    Example:

    db.users.aggregate([
      { $replaceRoot: { newRoot: "$address" } }
    ]);
    

    86. How do you perform bulk operations in MongoDB?

    Answer:

    You can perform bulk operations using the bulkWrite method, allowing you to execute multiple write operations in one call.

    Example:

    db.users.bulkWrite([
      { insertOne: { document: { name: "Bob" } } },
      { updateOne: { filter: { name: "Alice" }, update: { $set: { age: 27 } } } }
    ]);
    

    87. What is the countDocuments() method?

    Answer:

    The countDocuments() method counts the number of documents in a collection that match a specified query.

    Example:

    db.users.countDocuments({ age: { $gt: 25 } });
    

    88. What is the deleteMany() method?

    Answer:

    The deleteMany() method removes all documents that match a specified filter.

    Example:

    db.users.deleteMany({ age: { $lt: 18 } });
    

    89. What is the purpose of the findOne() method?

    Answer:

    The findOne() method retrieves a single document that matches a specified filter.

    90. What is the updateMany() method?

    Answer:

    The updateMany() method updates all documents that match a specified filter.

    Example:

    db.users.updateMany({ age: { $lt: 18 } }, { $set: { status: "minor" } });
    

    91. What is the purpose of the createCollection() method?

    Answer:

    The createCollection() method creates a new collection in the database.

    92. What is the dropCollection() method?

    Answer:

    The dropCollection() method removes an entire collection from the database.

    Example:

    db.users.dropCollection();
    

    93. What is a capped collection in MongoDB?

    Answer:

    A capped collection is a fixed-size collection that maintains insertion order and automatically removes the oldest documents when it reaches its size limit.

    94. What is the purpose of the createIndex() method?

    Answer:

    The createIndex() method creates an index on a collection to improve query performance.

    Example:

    db.users.createIndex({ name: 1 });
    

    95. What is the difference between getCollection() and db.collection?

    Answer:

    • getCollection(): Returns a collection object.
    • db.collection: Directly accesses a collection as a property of the database object.

    96. What is a database in MongoDB?

    Answer:

    A database in MongoDB is a container for collections and provides a namespace for documents.

    97. How do you switch between databases in MongoDB?

    Answer:

    You can switch between databases using the use command.

    Example:

    use myDatabase;
    

    98. What is the difference between a document and a collection?

    Answer:

    • Document: A single record in a MongoDB database, represented as a BSON object.
    • Collection: A group of documents stored in a database.

    99. What is the role of the MongoDB shell?

    Answer:

    The MongoDB shell is an interactive JavaScript interface for querying and interacting with the MongoDB database.

    100. What is the $project stage in aggregation?

    Answer:

    The $project stage reshapes documents in the aggregation pipeline, allowing you to include, exclude, or add new fields.

    Example:

    db.users.aggregate([
      { $project: { name: 1, age: 1, isAdult: { $gte: ["$age", 18] } } }
    ]);