MongoDB
Beginner
1 min read
One-to-Many Relationships
Example
// ONE-TO-FEW — embed comments inside the blog post
db.posts.insertOne({
_id: ObjectId("post1"),
title: "MongoDB Schema Design",
// Comments are small in number and always accessed with the post
comments: [
{ author: "Alice", text: "Great post!", date: new Date() },
{ author: "Bob", text: "Very helpful.", date: new Date() }
]
})
// ONE-TO-MANY — reference the parent from the child
db.orders.insertOne({
_id: ObjectId("order1"),
userId: ObjectId("user1"), // reference back to users collection
total: 129.99,
status: "pending"
})
// Fetch all orders for a user
db.orders.find({ userId: ObjectId("user1") })
// ONE-TO-SQUILLIONS — reference parent from the many side
db.logs.insertOne({
_id: ObjectId(),
serverId: ObjectId("server1"), // reference, not embedded
level: "error",
message: "Disk usage at 95%",
timestamp: new Date()
})