{jsonbody.com}

Top 200 MongoDB Interview Questions and Answers

Prepare for database and backend interviews with our comprehensive collection of top 200 MongoDB interview questions, aggregation pipelines, indexing, and expert answers.

Q1. What is MongoDB?

MongoDB is an open-source, cross-platform, document-oriented NoSQL database designed for high performance, high availability, and easy scalability.

Q2. What is a NoSQL database?

NoSQL databases store data in flexible, schema-less or semi-structured formats (like JSON documents) rather than traditional rigid relational tables with rows and columns.

Q3. Why choose MongoDB over RDBMS?

MongoDB offers flexible schemas, horizontal scalability via sharding, high availability via replica sets, fast read/write performance, and natural JSON-based data representation.

Q4. What is BSON?

BSON (Binary JSON) is a binary-encoded serialization format used by MongoDB to store documents and make remote procedure calls.

Q5. What is a Document in MongoDB?

A document is a basic unit of data in MongoDB consisting of field-value pairs, analogous to a row in a relational database table.

Q6. What is a Collection in MongoDB?

A collection is a grouping of MongoDB documents, analogous to a table in a relational database.

Q7. What is the _id field?

The _id field is a mandatory unique 12-byte ObjectId automatically generated by MongoDB for every document, serving as the primary key.

Q8. What is an ObjectId composed of?

An ObjectId consists of a 4-byte timestamp, a 3-byte machine identifier, a 2-byte process ID, and a 3-byte counter.

Q9. Is MongoDB schema-less?

MongoDB is technically schema-flexible, meaning documents in the same collection do not need to have the exact same set of fields.

Q10. What is MongoDB Atlas?

MongoDB Atlas is a fully-managed cloud database service hosted across AWS, Azure, and Google Cloud.

Q11. What is WiredTiger storage engine?

WiredTiger is the default storage engine in MongoDB, providing features like document-level concurrency, checkpointing, and compression.

Q12. What is document-level concurrency?

A concurrency model where multiple clients can modify different documents in the same collection simultaneously without locking the entire table.

Q13. What is replica set in MongoDB?

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

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

The primary node receives all write operations and replicates them to secondary nodes.

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

Secondary nodes replicate data from the primary node and can handle read operations or be elected as primary if the current primary fails.

Q16. What is an arbiter in MongoDB?

An arbiter is a lightweight member of a replica set that does not hold data but participates in elections to break ties.

Q17. What is automatic failover?

The automatic election process where secondary nodes elect a new primary node if the existing primary goes offline.

Q18. What is Sharding?

Sharding is a method for distributing data across multiple physical machines to support deployments with large datasets and high throughput.

Q19. What are the components of a sharded cluster?

Shards (store data), Query Routers (mongos routing client requests), and Config Servers (store cluster metadata).

Q20. What is a shard key?

An indexed field or compound fields in a collection that determines how data is distributed across shards.

Q21. What is ranged sharding vs hashed sharding?

Ranged sharding groups documents by shard key ranges, while hashed sharding computes an MD5 hash of the shard key to distribute data evenly.

Q22. What is chunk migration in sharding?

The background process of moving data chunks between shards to maintain balanced cluster storage.

Q23. What is a Namespace in MongoDB?

A concatenation of the database name and collection name (e.g., 'shop.orders').

Q24. What is MongoDB Compass?

The official GUI for MongoDB allowing developers to visualize data, run queries, and analyze performance.

Q25. What is mongosh?

The modern, fully-featured JavaScript/Node.js-based command-line shell for interacting with MongoDB.

Q26. What is oplog in MongoDB?

The operations log (local.oplog.rs) is a special capped collection that records all operations modifying data in the database, used for replication.

Q27. What are capped collections?

Fixed-size collections that automatically overwrite oldest data when they reach their maximum size limit while maintaining insertion order.

Q28. What is database profiling?

A diagnostic tool collecting detailed information about slow database queries and operations.

Q29. What is write concern?

The level of acknowledgment requested from MongoDB for write operations to guarantee durability (e.g., w: 1, w: 'majority').

Q30. What is read concern?

Controls the consistency and isolation of data read from replica sets (e.g., 'local', 'majority', 'linearizable').

Q31. What is read preference?

Directs read operations from client applications to specific replica set members (e.g., primary, secondaryPreferred).

Q32. What is journaling in MongoDB?

A write-ahead log mechanism writing operations to disk before applying them to data files, ensuring crash recovery.

Q33. What is data modeling in MongoDB?

Designing database schemas based on application access patterns (embedding vs referencing).

Q34. When should you use embedding?

When data has a one-to-few relationship or objects are frequently accessed together.

Q35. When should you use referencing (normalization)?

When data has one-to-many or many-to-many relationships with large datasets or frequently changing sub-documents.

Q36. How do you insert documents in MongoDB?

Using db.collection.insertOne() or db.collection.insertMany().

Q37. How do you query documents in MongoDB?

Using db.collection.find() with query selector objects.

Q38. What is projection in MongoDB queries?

Specifying which fields to include or exclude in the returned query result documents.

Q39. How do you update documents?

Using db.collection.updateOne(), db.collection.updateMany(), or db.collection.replaceOne().

Q40. How do you delete documents?

Using db.collection.deleteOne() or db.collection.deleteMany().

Q41. What are update operators in MongoDB?

Operators like $set, $inc, $push, $pull, $unset used to modify document fields.

Q42. What does the $set operator do?

Replaces the value of a field with the specified value or creates the field if it doesn't exist.

Q43. What does the $inc operator do?

Increments a numeric field value by a specified amount.

Q44. What does the $push operator do?

Appends a specified value to an array field.

Q45. What does the $pull operator do?

Removes all instances of a value from an existing array matching a condition.

Q46. What is the $addToSet operator?

Adds a value to an array only if it does not already exist, preventing duplicates.

Q47. How do you sort query results?

Using .sort({ field: 1 }) for ascending or -1 for descending order.

Q48. How do you limit and skip query results?

Using .limit(n) to restrict results and .skip(n) to bypass initial documents (used for pagination).

Q49. What is the $in operator?

Matches any of the values specified in an array.

Q50. What is the $exists operator?

Matches documents that have or do not have a specified field.

Q51. What is the $type operator?

Selects documents if a field is of a specified BSON data type.

Q52. How do you perform regex text searches in queries?

Using $regex operator or regex literals for pattern matching.

Q53. What is text search in MongoDB?

Performing linguistic searches across text fields using specialized text indexes and the $text query operator.

Q54. What is geospatial indexing in MongoDB?

Indexing and querying spatial coordinate data using 2dsphere indexes and operators like $geoIntersects or $near.

Q55. What is the $all operator?

Matches arrays that contain all specified elements.

Q56. What is the $elemMatch operator?

Matches documents that contain an array field with at least one element satisfying all specified query criteria.

Q57. What is the $size operator?

Matches arrays that have a specified number of elements.

Q58. How do you count documents in a collection?

Using db.collection.countDocuments() or estimatedDocumentCount().

Q59. How do you get distinct field values?

Using db.collection.distinct('fieldName').

Q60. What is upsert option in updates?

When upsert: true, MongoDB creates a new document if no documents match the update filter criteria.

Q61. What is findOneAndUpdate()?

An atomic operation that finds a matching document, updates it, and returns either the old or updated document.

Q62. What is bulkWrite?

Performs multiple write operations (inserts, updates, deletes) in bulk for higher performance.

Q63. What are dot notation queries?

Accessing nested document fields or array elements using dot syntax (e.g., 'address.city' or 'grades.0').

Q64. How do you query elements inside arrays?

Using field paths directly or array operators like $elemMatch.

Q65. What is query selectivity?

The ability of a query filter to narrow down and exclude a large percentage of documents.

Q66. What is the $expr operator?

Allows use of aggregation expressions within standard query language.

Q67. What is the $where operator?

Allows running arbitrary JavaScript expressions in queries (discouraged due to performance impact).

Q68. How do you handle null or missing fields in queries?

Using $eq: null which matches both null values and missing fields.

Q69. How do you check if a field is strictly null?

Using { field: { $type: 10 } } (BSON type null).

Q70. What is query timeout option?

Setting maxTimeMS to abort queries taking longer than a specified duration.

Q71. What is the sort memory limit?

MongoDB limits in-memory sort operations to 100MB unless allowDiskUse() is enabled.

Q72. How do you copy collections?

Using aggregate $out stages or database backup/restore utilities.

Q73. What is drop vs deleteMany?

drop() completely deletes a collection and its indexes from disk instantly, whereas deleteMany() removes documents one by one.

Q74. What is capped collection restriction on updates?

Documents in capped collections cannot be updated if the update increases document size.

Q75. How do you check current executing operations?

Using db.currentOp().

Q76. What is an Index in MongoDB?

A data structure storing a small portion of the collection's data in an easy-to-traverse form to speed up query execution.

Q77. What is the default index in MongoDB?

The unique index created automatically on the _id field.

Q78. What is a Single Field Index?

An index created on a single field of a document.

Q79. What is a Compound Index?

An index created on multiple fields of a document (e.g., { status: 1, createdAt: -1 }).

Q80. What is the ESR rule in compound indexes?

Equality, Sort, Range rule: design compound indexes placing Equality fields first, Sort fields second, and Range fields last.

Q81. What is a Multikey Index?

An index created on an array field that automatically indexes every element of the array.

Q82. What is a Text Index?

An index supporting string search queries on string content.

Q83. What is a Wildcard Index?

An index indexing all fields in documents or subdocuments automatically, useful for unpredictable schemas.

Q84. What is a Partial Index?

An index built only on documents that meet a specified filter expression, saving storage space.

Q85. What is a Sparse Index?

An index that only indexes documents containing the indexed field, ignoring documents where the field is missing.

Q86. What is a TTL (Time-To-Live) Index?

A special index that automatically deletes documents from a collection after a certain time period.

Q87. What is a Unique Index?

An index ensuring that the indexed fields do not store duplicate values across documents.

Q88. How do you check if a query uses an index?

Using .explain('executionStats') on a query.

Q89. What is COLLSCAN?

Collection Scan: indicates MongoDB scanned every document in the collection because no suitable index was found.

Q90. What is IXSCAN?

Index Scan: indicates MongoDB successfully utilized an index to resolve the query.

Q91. What is Covered Query?

A query where all requested fields are part of an index, and the query returns data directly from the index without inspecting documents.

Q92. How do indexes impact write performance?

Every index must be updated whenever a document is inserted, modified, or deleted, adding overhead to write operations.

Q93. How do you drop an index?

Using db.collection.dropIndex('indexName').

Q94. What is background index building?

Building indexes in the background so collection read/write operations aren't blocked (default in modern MongoDB).

Q95. What is index intersection?

The ability of MongoDB to combine multiple indexes to fulfill a query when a single compound index isn't available.

Q96. What is query plan cache?

MongoDB caches the most efficient execution plan for queries to speed up subsequent identical queries.

Q97. What is index bloat?

When indexes grow larger than available RAM, causing frequent disk reads and performance degradation.

Q98. How do you reindex a collection?

Using db.collection.reIndex() to rebuild all indexes.

Q99. What is the maximum number of indexes per collection?

64 indexes.

Q100. What is query optimization best practice?

Creating proper indexes, selecting required fields via projection, avoiding regex leading wildcards, and limiting returned document counts.

Q101. What is the Aggregation Framework?

A framework for processing data through a pipeline of stages, transforming documents into aggregated results.

Q102. What is an Aggregation Pipeline?

A sequence of stages where each stage transforms the documents as they pass through.

Q103. What does the $match stage do?

Filters documents to pass only those matching specified conditions (equivalent to SQL WHERE).

Q104. What does the $group stage do?

Groups documents by a specified expression and applies accumulator expressions like $sum, $avg.

Q105. What does the $project stage do?

Reshapes documents by adding, renaming, or dropping fields (equivalent to SQL SELECT).

Q106. What does the $sort stage do?

Sorts all input documents by specified sort keys.

Q107. What does the $limit stage do?

Restricts the number of documents passing through the pipeline.

Q108. What does the $skip stage do?

Skips a specified number of documents in the pipeline.

Q109. What does the $unwind stage do?

Deconstructs an array field from input documents to output a document for each element.

Q110. What does the $lookup stage do?

Performs a left outer join to another collection in the same database (like SQL JOIN).

Q111. What does the $addFields stage do?

Adds new fields to documents.

Q112. What does the $out stage do?

Writes resulting documents of the aggregation pipeline to a specified collection.

Q113. What does the $merge stage do?

Writes aggregation results into a collection with options to insert, update, or replace existing documents.

Q114. What is the difference between $out and $merge?

$out replaces an entire collection, whereas $merge can merge results into an existing collection incrementally.

Q115. What does the $facet stage do?

Processes multiple aggregation pipelines within a single stage on the same set of input documents.

Q116. What does the $bucket stage do?

Categorizes incoming documents into groups (buckets) based on specified boundaries.

Q117. What is the $sample stage?

Selects a random set of documents from the input collection.

Q118. What is the $graphLookup stage?

Performs a recursive search on a collection to handle hierarchical tree data structures.

Q119. How do you optimize aggregation performance?

Place $match and $sort stages at the very beginning of the pipeline to leverage indexes and reduce data volume.

Q120. What is aggregation memory limit?

Aggregation stages have a 100MB RAM limit per stage unless allowDiskUse(true) is enabled.

Q121. What is the $redact stage?

Restricts the content of documents based on stored document-level security metadata.

Q122. What is the $count stage?

Returns a document with the number of documents entering the stage.

Q123. What is the $skip vs $limit optimization in pipelines?

MongoDB automatically optimizes query pipelines placing limits before skips when appropriate.

Q124. How do you calculate averages in aggregation?

Using { $avg: '$fieldName' } inside a $group stage.

Q125. What is conditional expression in aggregation?

Using $cond or $switch to execute conditional logic within projections or groupings.

Q126. Does MongoDB support transactions?

Yes, MongoDB supports multi-document ACID transactions across replica sets and sharded clusters.

Q127. When should you use transactions in MongoDB?

Only when atomic updates across multiple documents or collections are strictly required; single-document updates are atomic by default.

Q128. What is document atomicity?

Write operations on a single document are fully atomic, even if they modify nested sub-documents or arrays.

Q129. How do you start a transaction in Node.js (Mongoose)?

Using session = await mongoose.startSession(), session.startTransaction(), and passing { session } in queries.

Q130. What is RBAC in MongoDB?

Role-Based Access Control restricting database access based on user roles and privileges.

Q131. What are built-in roles in MongoDB?

Roles like read, readWrite, dbAdmin, clusterAdmin, and root.

Q132. How do you enable authentication in MongoDB?

By configuring the security.authorization: enabled setting in mongod.conf.

Q133. What is TLS/SSL in MongoDB?

Encrypts all network traffic between clients and servers or between cluster members.

Q134. What is encryption at rest?

Encrypting database storage files on disk to prevent unauthorized physical data access.

Q135. What is mongodump and mongorestore?

Utilities used to create binary database backups (dumps) and restore them.

Q136. What is mongoexport and mongoimport?

Utilities used to export and import collection data in JSON or CSV formats.

Q137. What is MongoDB Ops Manager / Cloud Manager?

Enterprise monitoring, backup, and automation management tools for MongoDB deployments.

Q138. What is change streams in MongoDB?

A feature allowing applications to access real-time data changes without the complexity of tailing oplogs.

Q139. How do change streams work?

They use aggregation framework syntax to listen to insert, update, delete, and replace events on collections or databases.

Q140. What is GridFS?

A specification for storing and retrieving large files (exceeding the 16MB BSON document limit) by splitting them into chunks.

Q141. How does GridFS store files?

Using two collections: fs.files (metadata) and fs.chunks (binary file data blocks).

Q142. What is the maximum BSON document size?

16 megabytes.

Q143. What is Mongoose ODM?

An Object Data Modeling library for Node.js providing schema definition, type casting, validation, and query building.

Q144. What is a Mongoose Schema?

A blueprint mapping to a MongoDB collection, defining document shape, types, defaults, and validators.

Q145. What is the difference between Mongoose Model and Document?

A Model is a constructor compiling documents from schemas, whereas a Document is an instance of a model representing a single database record.

Q146. What is populate() in Mongoose?

Automatically replaces specified paths in document references with documents from other collections (joins).

Q147. What are Mongoose middleware (hooks)?

Functions executed before or after specific operations like save, remove, validate, or find (pre and post hooks).

Q148. What are virtuals in Mongoose?

Document properties that you can get and set but that are not persisted in MongoDB storage.

Q149. What is Mongoose discriminator?

A schema inheritance modeling feature enabling multiple models with overlapping schemas to share the same underlying collection.

Q150. How do you handle connection pooling in Mongoose?

Configured automatically via connection settings (maxPoolSize, minPoolSize).

Q151. What is strict mode in Mongoose schemas?

Ensures fields not specified in the schema are not saved to the database.

Q152. What is lean queries in Mongoose?

Queries returning plain JavaScript objects instead of heavy Mongoose documents, boosting read performance significantly.

Q153. How do you handle database migrations in MongoDB?

Using migration libraries like migrate-mongo or custom scripts tracking migration state versions.

Q154. What is capped collection use case?

Logging, caching recent activity logs, or storing audit trails where older logs can be safely overwritten.

Q155. What is time-series collections in MongoDB?

Specialized collections optimized for storing time-series data with automatic compression and efficient range queries.

Q156. What is replica set election timeout?

The duration secondary nodes wait before triggering an election if they lose contact with the primary node.

Q157. What is split brain syndrome?

A network partitioning issue where two parts of a cluster operate independently; replica sets prevent this using majority voting.

Q158. What is a delayed replica set member?

A secondary node configured to lag behind the primary by a specified time, protecting against accidental data deletions.

Q159. What is hidden member in replica set?

A secondary node invisible to client applications, often used for backups or analytics reporting.

Q160. What is priority 0 member?

A secondary node that cannot become the primary in an election.

Q161. What is index build blocking in older vs modern MongoDB?

Older versions blocked collection writes during index builds; modern versions build indexes concurrently in the background.

Q162. What is compact command?

Reclaims disk space by defragmenting collection data and index files.

Q163. What is repairDatabase?

Rebuilds corrupted database files (deprecated in favor of more robust recovery mechanisms).

Q164. What is serverless MongoDB?

MongoDB Atlas Serverless instances scaling compute resources automatically based on actual traffic demand.

Q165. What is collection validation rules?

JSON schema rules enforcing strict data validation criteria on inserts and updates.

Q166. What is WiredTiger cache size?

Typically configured to use 50% of (total RAM - 1GB) by default.

Q167. What is checkpointing in WiredTiger?

Writing in-memory dirty data to disk periodically to create a consistent point-in-time snapshot.

Q168. What is memory-mapped files in older storage engines?

Allocating virtual memory matching file sizes so the OS manages disk paging (used by MMAPv1).

Q169. Why was MMAPv1 deprecated?

Due to collection-level locking bottlenecks and lack of native document-level concurrency.

Q170. What is query plan cache flush?

Clearing cached query plans when indexes are modified or collection statistics change significantly.

Q171. What is hint() in queries?

Forces MongoDB to use a specific index for executing a query.

Q172. What is sort() memory limit error workaround?

Enabling allowDiskUse() on aggregation or sorting pipelines.

Q173. What is bulk insert batch size limit?

Maximum 1000 operations per bulk write batch.

Q174. What is max wire version?

Protocol version determining compatibility between client drivers and database servers.

Q175. How do you monitor MongoDB performance?

Using mongostat, mongotop, MongoDB Cloud Manager, or Prometheus/Grafana exporters.

Q176. What is mongostat?

A utility providing a quick overview of database operations (inserts, queries, updates, deletes, locking).

Q177. What is mongotop?

A utility measuring time spent reading and writing data across MongoDB collections.

Q178. What is collection statistics command?

Running db.collection.stats() to inspect storage size, index sizes, and document counts.

Q179. What is database statistics command?

Running db.stats() to inspect overall database storage metrics.

Q180. What is sh.status()?

A command in mongosh to inspect sharded cluster configuration, shards, and chunk distributions.

Q181. What is rs.status()?

Inspects replica set member health, states, and replication lag.

Q182. What is replication lag?

The time delay between an operation occurring on the primary node and its replication on secondary nodes.

Q183. How do you troubleshoot high CPU usage in MongoDB?

Checking slow query logs, identifying unindexed queries via profiler, or scaling compute resources.

Q184. How do you troubleshoot low disk space?

Checking oplog sizing, dropping unnecessary indexes, compacting collections, or scaling storage volumes.

Q185. What is free tier limitation in MongoDB Atlas?

Shared cluster limits (e.g., 512MB storage, M0 sandbox limitations).

Q186. What is MongoDB Realm / App Services?

A backend-as-a-service platform offering serverless functions, triggers, and device sync.

Q187. What is stitch triggers?

Serverless functions executing automatically on database change events.

Q188. What is schema versioning pattern?

Including a schemaVersion field inside documents to handle application data model evolution gracefully.

Q189. What is computed pattern in data modeling?

Pre-calculating and storing expensive aggregation results directly inside documents to speed up reads.

Q190. What is bucket pattern in data modeling?

Grouping time-series or sequential data into single documents to avoid millions of small records.

Q191. What is outliar pattern?

Handling high-frequency referencing arrays by separating or flagging outlier documents.

Q192. What is extended reference pattern?

Duplicating frequently accessed fields from referenced documents to reduce $lookup joins.

Q193. What is subset pattern?

Keeping a subset of frequently accessed child documents embedded while storing the rest separately.

Q194. What is polymorphic pattern in schemas?

Storing documents with varying structures in the same collection using a type discriminator field.

Q195. What is tree structures storage in MongoDB?

Storing hierarchical data using parent references, child references, or materialized paths.

Q196. What is materialized paths pattern?

Storing full ancestry paths inside string fields for lightning-fast tree subtree queries.

Q197. What is Nested Sets pattern?

Storing left and right boundary numbers for efficient hierarchical tree range queries.

Q198. How do you handle soft deletes in MongoDB?

Adding an isDeleted: true or deletedAt: timestamp field instead of physically removing documents.

Q199. Why are UUIDs sometimes preferred over ObjectIds?

UUIDs avoid exposing sequential insertion timestamps or when distributed systems generate unique keys client-side.

Q200. What is the future of MongoDB?

Enhanced vector search capabilities for AI/ML workloads, serverless scalability, multi-cloud clusters, and advanced stream processing.