Question library
Explained questions for the decisions developers make.
What are documents, collections, BSON and ObjectId?
MongoDB stores records as documents, which group related field values in one JSON-like structure. A collection holds documents, and BSON is the binary encoding that supports values such as dates and ObjectIds. An ObjectId is a common identifier format with a timestamp component, but it is not an authorization mechanism or a strict business ordering guarantee.
When should I embed data or reference it?
Embedding stores related data inside one document, while referencing stores a link to data in another document. Embedding makes related reads and single-document atomic updates convenient, but can duplicate data or create oversized documents. Referencing supports independently managed data at the cost of additional reads or joins.
How do I model relationships and schema changes?
Data modeling describes how records relate and how the application retrieves and changes them. Schema evolution is the process of changing that structure while old data and possibly old application versions still exist. MongoDB's flexible document shape makes gradual migration possible, but compatibility still needs planning.
What is denormalization?
Denormalization stores a fact in more than one place to make common reads simpler or faster. It trades extra storage and update work for fewer lookups. Some copies are historical snapshots, while others must track the current source of truth; those are different consistency requirements.
How do indexes help, and what do they cost?
An index is an extra data structure that helps the database find matching records without inspecting every document. Reads can become much faster, but inserts, updates and deletes must maintain the relevant indexes. Indexes are most useful when their fields and order match important query patterns.
What index types should I know?
MongoDB offers different index types because equality lookup, array search, text search, uniqueness and expiry have different needs. A compound index orders several fields together, while a partial index includes only documents matching a condition. TTL indexes support eventual cleanup rather than precise scheduling.
What is the ESR rule?
ESR stands for Equality, Sort and Range, a common starting point for ordering fields in a compound index. Equality fields narrow the relevant index region, sort fields can let MongoDB read in the desired order, and range fields constrain intervals. It is a guideline that must be checked against selectivity and the query plan.
What should I check in explain?
explain shows how MongoDB plans a query, and execution-statistics modes also show what work was performed. It helps distinguish an efficient index lookup from broad scanning, sorting or excessive document fetching. The goal is to understand why the query does work, not simply whether an index was selected.
How does an aggregation pipeline work?
An aggregation pipeline transforms documents through an ordered series of stages. Each stage filters, reshapes, groups or combines the previous output, allowing reporting work to run close to the data. Stage order matters for both the meaning of the result and the amount of work required.
What do lookup, unwind and facet do?
$lookup adds related data from another collection, $unwind expands an array into individual output records, and $facet runs multiple sub-pipelines on the same input. These operations change the shape or number of documents flowing through a pipeline. They are useful for joins and reports but can increase memory use and intermediate result size.
What do set, addFields, skip and count do?
These stages shape or limit pipeline output: $set/$addFields create or replace fields, $skip removes a leading number of results, and $count summarizes how many documents remain. Their position determines whether they operate on source records or already transformed results. A small final result does not mean the earlier work was small.
When do I need a transaction?
A transaction makes several database operations commit or roll back as a unit. MongoDB already makes single-document writes atomic, so a transaction is mainly needed when one business rule spans multiple documents. A session supplies transaction context; every participating operation must use that context.
Read concern vs write concern vs read preference?
Read concern, write concern and read preference control different parts of consistency and availability. Read concern controls which data a read may observe, write concern controls required acknowledgement, and read preference chooses eligible replica members. Combining them deliberately matters when an application expects to read a recent write or survive failover.
Replication vs sharding: what is the difference?
Replication keeps copies of data so a system can recover from node failure, while sharding distributes different subsets of data across nodes. Replica sets improve redundancy; sharding spreads storage and workload. A sharded deployment can also replicate each shard, so these techniques are complementary.
Schema vs model vs document in Mongoose?
A Mongoose schema defines document fields and behavior, and compiling it creates a model used for collection operations. A document is one hydrated record returned or created through that model. Hydration supplies methods and change tracking, which are useful for edits but add work compared with plain objects.
Populate vs lean: what should I remember?
populate resolves references so related records are available in a query result. lean skips creating full Mongoose document instances and returns plain JavaScript objects. One controls related-data retrieval and the other controls result hydration, so they solve different performance concerns.
What are hooks, virtuals, instance methods and static methods?
Hooks run around selected document or query operations, virtuals compute values that are not normally stored, and methods attach reusable behavior to documents or models. These features keep related logic near the data model. However, each feature has a defined execution context and does not apply to every write path automatically.
Is Mongoose validation enough to protect data?
Mongoose validation checks values against rules declared in a schema before supported operations complete. It improves input quality but cannot enforce every cross-document or concurrent business rule. Database constraints, conditional updates and authorization checks remain necessary because other writers or races may bypass application checks.
Difficulty is an editorial estimate. Completion means you chose to mark a question as understood.