Firestore Arrays, Lists and Sub-collections

Deepak Prasad
Mar 18 · 2 min read

Firestore doesn't support storing sub-collections into Objects as List<Object> nor does it support operations on sub-collections to filter current documents.

Sample Firestore Database

Consider the example in the picture above. It has Orders as collections and each Order needs to have Quotations (from many retailers).

Suppose we need to filter if a certain Retailer (say retailer_one) has submitted a quotation or not. Firestore doesn’t allow to perform queries on subcollections to filter out parent documents.

Also the “quotations” subcollections are not automatically stored in a ArrayList.

Filter Parent Collection using Sub — collections

To perform this operation, we need a to perform some simple hacks and reconstruct our Data.

Consider this scenario : We want to filter if retailerJohn has added a quotation or not to the current order.

We can add a field “hasJohnQuoted” and set it to true whenever John quotes this order.

Also we can create a Firestore Arrays( demonstrated below ) and append to the array all the retailers who have quoted the order.

Firestore Arrays and Maps

To store a Sub-collection, we can use Firestore Arrays and store Maps in them. Consider the following example.

A sample Sub-collection in Array with Maps as elements

Firestore has two Operations on Arrays — arrayUnion and arrayRemove. Below is an example of arrayUnion where a new quotations is created and added to the existing quotations Array.

Here is and example of arrayRemove where an existing quotation is removed from the quotations Array.

I hope this tutorial helps you in some way or other. Feel free to give some feedback.

Thanks for reading.