MongoDB Interview Questions
MongoDB Interview Questions When to choose MongoDB over PostgreSQL? MongoDB: flexible/evolving schema, document-oriented data (nested objects), rapid prototypin…
MongoDB Interview Questions
When to choose MongoDB over PostgreSQL? MongoDB: flexible/evolving schema, document-oriented data (nested objects), rapid prototyping, horizontal sharding needs. PostgreSQL: complex queries, joins, ACID transactions, structured/relational data
What is the aggregation pipeline? Series of stages that transform documents: $match (filter), $group (aggregate), $sort, $project (shape), $lookup (join), $unwind (flatten arrays), $limit, $skip. Each stage output feeds the next
Embedding vs referencing documents? Embed when: data always retrieved together, child has no independent existence, reads > writes. Reference when: document size grows unboundedly, data shared across documents, independent access needed
How does sharding work? Horizontal partitioning across multiple nodes using a shard key. Range sharding: by value ranges (may cause hotspots). Hash sharding: even distribution. Choose a high-cardinality, evenly-distributed shard key
What is a replica set? Group of mongod instances maintaining same data: 1 primary (handles writes), ≥1 secondary (replicate async). Automatic failover — secondary becomes primary if primary goes down. Provides high availability
How to ensure data consistency? writeConcern: majority (wait for majority replica acknowledgment). readConcern: majority or linearizable. Multi-document ACID transactions available since MongoDB 4.0 (use sparingly — performance cost)
How to debug slow queries? db.collection.explain("executionStats") — check COLLSCAN (bad) vs IXSCAN (good), nScanned/nReturned ratio. Use MongoDB Atlas Performance Advisor or db.setProfilingLevel(1)