Skip to content

Data Modeling

One-to-Many Relationships

Orders for a user, items in an order — embed the small side, reference the growing side.

IntermediateAbout 6 minutes

One-to-many is two different shapes. Few, owned, loaded with the parent → embed the array. Many, or queried alone → child documents with parentId. The commerce dataset does both on purpose.

Embed the many

  • order.items — a handful of lines
  • Always rendered with the order
  • Not a product page
  • Cap is 'this checkout'

Reference the many

  • orders.userId — years of checkouts
  • Order history is its own query
  • Index { userId: 1, createdAt: -1 }
  • No cap
// Fine — a wishlist of tens, not millions
{ name: "Rahul", wishlist: [ObjectId("…keyboard"), ObjectId("…cable")] }

// Not fine — every order id Rahul ever placed
{ name: "Rahul", orderIds: [ /* 4000 ObjectIds and growing */ ] }
Third shape: bounded array of ids on the parent

Prefer parent id on the child (orders.userId) over child ids on the parent once the list can grow. The child collection indexes the foreign key. The parent document stays small. An array of ids is for a capped set you always load with the parent (roles, featured product ids).

Interview question

How do you model one-to-many in MongoDB?

Think about it first.

Practice

Embedded lines vs referenced orders — both show up in practice.