An orders collection in the document database MongoDB embeds an array of line items — how do you land it in a warehouse?
Split by grain: an orders table with one row per document and an order_items table with one row per array element, keyed by order _id plus position. One flat wide table repeats order fields on every item, so summed order totals inflate.
- Unwinding the array into one table and then summing order-level amounts such as shipping or discount across its rows
- Keying the child table by the item's position alone, so a reload or a reordered array cannot be matched back to its order
- Leaving the array as a JSON string in the warehouse and parsing it in every report
- The application edits one line item in place — how do you update
order_itemswithout duplicates? - When would you reference line items from a separate collection instead of embedding them in MongoDB?
The source document. MongoDB stores together what is read together: an order carries its line items inside.
{ "_id": "o-1001", "customer_id": "c-7", "shipping_fee": 300,
"items": [ { "sku": "A-1", "qty": 2, "price": 500 },
{ "sku": "B-9", "qty": 1, "price": 1200 } ] }Two tables, by grain. A document is one order, an array element is one line item; they have different grains, so they get different tables:
-- one row per document
INSERT INTO orders (order_id, customer_id, shipping_fee) VALUES ('o-1001', 'c-7', 300);
-- one row per array element; key = (order_id, item_pos)
INSERT INTO order_items (order_id, item_pos, sku, qty, price) VALUES
('o-1001', 0, 'A-1', 2, 500),
('o-1001', 1, 'B-9', 1, 1200);What goes wrong with one table. After $unwind (or Spark's explode), shipping_fee = 300 sits on both rows and SUM(shipping_fee) returns 600. It is the same mixed-grain error as in a star schema, produced here by a nested array.
The item key. An array position works as a key only together with the order _id; if the application can reorder items, a line-item id stored in the document is safer. When an order changes, the simplest correct update is to rebuild all its rows in order_items (delete and insert by order_id) rather than guess which element moved.
The limit of embedding. A MongoDB document is capped at 16 MiB, so arrays that grow without bound (every review of a product) live in a separate collection with a reference — and reach the warehouse as a separate table from the start.