Data Modeling
One-to-Many Relationships
Orders for a user, items in an order — embed the small side, reference the growing side.
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 */ ] }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?
If the many side is small, owned, and always read with the parent — embed it, like line items on an order. If it grows or is queried on its own — put parentId on the child, like userId on orders. An array of child ids on the parent is only for a bounded list.
Practice
Embedded lines vs referenced orders — both show up in practice.