One-to-Many Relationships
Model one-to-many relationships by embedding for small sets or referencing for large sets.
Example
// Embedded (few comments per post)
{
"_id": 1,
"title": "Learn MongoDB",
"comments": [
{ "user": "Bob", "text": "Helpful!" }
]
}
// Referenced (many orders per user)
// users collection
{ "_id": "user1", "name": "Alice" }
// orders collection
{ "_id": "order1", "userId": "user1", "total": 99.99 }
{ "_id": "order2", "userId": "user1", "total": 49.99 }
// Query with $lookup
db.users.aggregate([
{ $lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "orders"
}}
]) Many-to-Many Relationships
For many-to-many relationships, store arrays of references in one or both documents.
Example
// Students and Courses — many-to-many
// students collection
{
"_id": "s1",
"name": "Alice",
"courseIds": ["c1", "c2", "c3"]
}
// courses collection
{
"_id": "c1",
"title": "Web Development",
"studentIds": ["s1", "s2"]
}
// Find all courses for a student
db.courses.find({ studentIds: "s1" })
// Find all students in a course
db.students.find({ courseIds: "c1" }) 