MongoDB is the most widely used NoSQL database in Indian product companies, powering the Node.js stacks at Razorpay, Swiggy, Zomato, and dozens of Indian startups. MongoDB interviews test the document model, aggregation pipeline, indexing strategies, and high-availability concepts like replica sets and sharding.
Document Model, BSON, and CRUD Operations
MongoDB stores data as documents rather than rows in tables. Understanding the document model and BSON is the foundation for MongoDB interviews.
Document model vs relational:
- MongoDB stores data as BSON documents (Binary JSON) in collections
- Collections are analogous to tables; documents are analogous to rows
- Each document can have a different structure (schema-flexible); there is no enforced schema by default
- Documents can embed related data (embedded documents and arrays) instead of using joins
- Embedding vs referencing: embed when data is always accessed together and the embedded data is not too large; reference (store ObjectId of the related document) when data is accessed independently or shared by many documents
BSON (Binary JSON):
- BSON is the binary serialisation format MongoDB uses to store and transfer documents
- BSON supports types not in JSON: ObjectId (12-byte unique ID: 4 bytes timestamp + 5 bytes random + 3 bytes counter), Date, Binary, Decimal128, Int32, Int64, Boolean, Null
- Every MongoDB document has a required _id field; if not provided, MongoDB generates an ObjectId automatically
CRUD operations:
- insertOne({ name: 'Alice', age: 30 }) — insert a single document
- insertMany([{...}, {...}]) — insert multiple documents
- findOne({ age: { $gt: 25 } }) — find the first document where age > 25
- find({ status: 'active' }).sort({ name: 1 }).limit(10) — find with sort and limit
- Query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $and, $or, $nor, $not, $regex, $exists
- updateOne({ _id: id }, { $set: { status: 'inactive' } }) — update one field
- updateMany({ status: 'pending' }, { $set: { status: 'active' } }) — update multiple documents
- $set (set fields), $unset (remove fields), $push (add to array), $pull (remove from array), $inc (increment), $addToSet (add to array if not present)
- deleteOne({ _id: id }) — delete one document
- deleteMany({ createdAt: { $lt: cutoffDate } }) — delete multiple documents
- replaceOne — replaces the entire document except _id
- Upsert: { upsert: true } in update options — insert if no document matches the filter
Aggregation Pipeline and Indexing Strategies
The aggregation pipeline is MongoDB's most powerful data transformation tool and is heavily tested in interviews at Indian product companies.
Aggregation pipeline:
- A pipeline is a sequence of stages; each stage transforms the documents and passes the result to the next stage
- $match: filter documents early in the pipeline (like a WHERE clause); place $match as early as possible to reduce the number of documents processed by downstream stages
- $group: group documents by a key and compute aggregations: { _id: '$status', count: { $sum: 1 }, total: { $sum: '$amount' } }
- Accumulator operators in $group: $sum, $avg, $min, $max, $count, $push (collect values into an array), $addToSet (collect unique values)
- $project: reshape documents — include or exclude fields, add computed fields: { name: 1, fullName: { $concat: ['$firstName', ' ', '$lastName'] } }
- $sort: sort documents: { amount: -1 } (descending), { name: 1 } (ascending)
- $limit and $skip: pagination
- $lookup: left outer join with another collection: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user' }
- $unwind: deconstruct an array field into separate documents (one document per array element); useful before $group on array elements
- $addFields: add new fields to documents without removing existing fields
- $count: count the number of documents at this stage of the pipeline
Indexing strategies:
- Single field index: db.collection.createIndex({ email: 1 }) — ascending index on email
- Compound index: db.collection.createIndex({ status: 1, createdAt: -1 }) — important: field order matters; the index supports queries on status alone and on (status, createdAt) combined
- The ESR rule: place Equality filters first, Sort fields second, Range filters third in compound indexes
- Multikey index: automatically created when a field contains an array; indexes each array element
- Text index: db.collection.createIndex({ description: 'text' }) — enables full-text search with $text operator
- Partial index: { partialFilterExpression: { status: 'active' } } — only indexes documents matching the filter; smaller index, faster queries on the filtered subset
- TTL (Time To Live) index: { expireAfterSeconds: 3600 } — MongoDB automatically deletes documents after the TTL expires; used for sessions, logs, cache entries
- explain(): use db.collection.find({...}).explain('executionStats') to analyse query performance; look for COLLSCAN (collection scan — no index used) vs IXSCAN (index scan)
Replica Sets, Sharding, and Schema Design Patterns
Replica sets and sharding are tested for senior MongoDB roles and at companies running MongoDB in production at scale.
Replica sets:
- A replica set is a group of MongoDB nodes that maintain the same data; provides high availability and automatic failover
- Primary: the single node that accepts all write operations; replicates writes to secondaries via the oplog (operation log)
- Secondary: replicates from the primary; can serve reads (if configured); automatically elected as new primary if the current primary goes down
- Arbiter: votes in elections but does not hold data; used when you want an odd number of voting members without the cost of a full data-bearing node
- Write concern: controls acknowledgement before returning success to the client; w:1 (primary acknowledged), w:'majority' (majority of voting members acknowledged — safer, higher latency)
- Read preference: primaryPreferred (read from primary; fall back to secondary), secondary (always read from secondary — may return stale data), nearest (lowest network latency)
- Oplog: a capped collection that records all write operations in order; secondaries tail the oplog to replicate
Sharding:
- Sharding is horizontal scaling — data is distributed across multiple replica sets (shards)
- Shard key: the field(s) used to determine which shard a document belongs to; chosen at collection creation; cannot be easily changed later
- Range-based sharding: documents are distributed based on shard key value ranges; efficient for range queries but risks hotspots for monotonically increasing keys (like ObjectId or timestamp)
- Hashed sharding: MongoDB hashes the shard key value; distributes data evenly; poor for range queries
- Chunk: MongoDB divides the shard key space into chunks; chunks are migrated between shards by the balancer to maintain even distribution
- mongos: the query router that routes requests to the correct shard(s); clients connect to mongos, not directly to shards
Schema design patterns:
- Bucket pattern: group related time-series data into documents (e.g., one document per hour with an array of measurements); reduces document count and improves range query performance
- Computed pattern: pre-compute frequently accessed aggregations (e.g., order total) and store them in the document to avoid expensive real-time aggregation
- Subset pattern: store a subset of related data (e.g., the last 10 reviews) in the parent document; store the full list in a separate collection
Frequently asked questions
Explore more