MongoDB & NoSQL (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What is the difference between Embedding and Referencing documents?
junior LevelCode ExamplemongodbBasic
In Simple Words: The fundamental data modeling decision in MongoDB:
- Embedding (Denormalization - 1-to-few): Child data is stored directly inside the parent document as an array or object.
- Pros: Fetched in a single fast read operation without JOINs.
- Cons: Subject to 16 MB document size limit; can lead to data duplication.
- Referencing (Normalization - 1-to-many / 1-to-squillions): Storing the child
_idin the parent document or vice versa (similar to foreign keys).- Pros: Avoids 16 MB document limit, eliminates duplication.
- Cons: Requires multiple queries or
$lookupaggregation joins.
text
Embedding vs Referencing:
Embedding: { _id: 1, name: "Order", items: [{ name: "Pen", price: 2 }] }
Referencing: { _id: 1, name: "Order", itemIds: [101, 102] } -> Items in separate collection