In MongoDB, a one-to-many relationship can be modeled in multiple ways, depending on the use case and access patterns. The two most common approaches are embedding and referencing.
1. Embedding (Denormalization) - Best for Read-Heavy Operations
In this approach, related documents are stored within the parent document as an array.
Example: One author has many books (Embedded Approach)
{
"_id": ObjectId("60f7c0b0c25f6d4d3c4b1e1f"),
"name": "J.K. Rowling",
"books": [
{ "title": "Harry Potter and the Sorcerer’s Stone", "year": 1997 },
{ "title": "Harry Potter and the Chamber of Secrets", "year": 1998 }
]
}
2. Referencing (Normalization) - Best for Write-Heavy & Large Collections
In this approach, related documents are stored separately, and the relationship is maintained using references (_id).
Example: Separate authors and books collections with references
// Authors Collection
{
"_id": ObjectId("60f7c0b0c25f6d4d3c4b1e1f"),
"name": "J.K. Rowling"
}
// Books Collection
{
"_id": ObjectId("60f7c0b0c25f6d4d3c4b1e2a"),
"title": "Harry Potter and the Sorcerer’s Stone",
"year": 1997,
"author_id": ObjectId("60f7c0b0c25f6d4d3c4b1e1f")
}
Query Example (Joining Data)
db.books.aggregate([
{
$lookup: {
from: "authors",
localField: "author_id",
foreignField: "_id",
as: "author_details"
}
}
])