How should you structure Firestore data using subcollections and denormalization to design efficient queries, given that Firestore does not support traditional relational joins across separate collections?
Short answer
Since Firestore is a NoSQL database that does not support traditional relational style joins across separate collections the way a SQL database would, designing an efficient Firestore data structure often means deliberately denormalizing data, meaning intentionally duplicating…
Advertisement
AModel answer
Since Firestore is a NoSQL database that does not support traditional relational style joins across separate collections the way a SQL database would, designing an efficient Firestore data structure often means deliberately denormalizing data, meaning intentionally duplicating certain frequently needed pieces of information across multiple documents to avoid needing a separate query, and organizing closely related data using subcollections nested beneath a parent document, such as storing a specific order's individual line items as a subcollection beneath that order's own document, which allows most common queries to be satisfied efficiently with a single request rather than several separate ones.
orders/{orderId}/items/{itemId}
// Denormalized customer name stored directly on the order for quick display
{ 'customerName': 'Alex', 'total': 49.99 }Real-world example
An order management system stores each order's individual line items as a Firestore subcollection nested beneath that specific order document, and also denormalizes the customer's name directly onto the order document itself, avoiding a separate query just to display the customer's name in an order list.
Likely follow-ups
- What are the tradeoffs of denormalizing data versus needing to keep duplicated data properly synchronized over time?
- When would using a subcollection be preferable to simply storing an array field directly within the parent document?
Related topics