Home > database >  Flutter Firebase Query on nested value in subcollection
Flutter Firebase Query on nested value in subcollection

Time:01-12

I am looking for a way to query a stream based on information in a subcollection.

Here is an example:

I have a Subcollection of Tickets. Each Ticket has a Subcollection of Companies involved in this Ticket. Each Company has a CEO as a Map. This Map has a field "id".

I now want to query the following thing: Get me a stream of all tickets where a company in this Ticket has a CEO with id "X".

I tried the following: refToTickets.where('companies.ceo.id', isEqualTo: CEOId).snapshots();

This doesn't work unfortunately.

CodePudding user response:

Firestore queries can only filter on values that are present in the documents that they return. So you can't filter tickets on values from the companies in the subcollection.

As usual when dealing with NoSQL databases, you'll want to modify/expand your data model to allow the use case. Here for example, you could store the company CEOs in a single array field for each ticket and query on that. So each time you write/delete a document, you also update the companyCEOs field in the corresponding ticket.

  • Related