MongoDB stores data as BSON documents, enabling flexible schemas and nested structures. The aggregation pipeline ($match, $group, $lookup, $project) replaces SQL joins and GROUP BY. Indexes use B-trees; compound indexes follow the ESR rule (Equality, Sort, Range). Change streams enable real-time reactions to data changes without polling. Multi-document ACID transactions are available since v4.0 but add overhead — prefer single-document operations where possible.
Aggregation pipeline for total revenue per customer.
MongoDB schema design is query-driven. Embed data that is always read together. Reference data that is queried independently or grows without bound.
Equality → Sort → Range. If your query is WHERE userId=X ORDER BY createdAt, the index should be {userId:1, createdAt:-1}. Putting range before sort wastes the sort optimization.
db.collection.find(query).explain("executionStats") shows whether a COLLSCAN (full scan) or IXSCAN is used. A COLLSCAN on a large collection is an outage waiting to happen.
Sign in to share your feedback and join the discussion.