SyntaxStudy
Sign Up
MongoDB One-to-Many Relationships
MongoDB Beginner 1 min read

One-to-Many Relationships

One-to-many relationships in MongoDB can be modelled in three ways depending on the cardinality and access patterns. For one-to-few (a blog post with a handful of comments), embed the many side as an array inside the one document. For one-to-many (a user with hundreds of orders), store a reference in the many side pointing back to the one side — this mirrors the relational foreign key pattern. For one-to-squillions (a server with millions of log entries), store a reference in the many documents to the parent, and never try to embed all of them. The key question to ask is always: "Which side of the relationship is accessed with the other, and how large can the many side grow?"
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()
})