2

Consider the following Firestore structure:

  • Collection people
  • Every document in the collection has a subcollection pets
  • Subcollection pets has multiple documents with pet data.

Now, I want to query for people whose pets satisfy certain conditions. Such as, people who have more than two pets, or who own a pet whose name is "ABC".

Is this possible?

Vlop
  • 53
  • 4

1 Answers1

3

The first example query you listed ("people who have more than two pets") is not possible with your current set of data. There are no counting or aggregate operations provided by Firestore. If you want to count things, you will need to get all the documents and count them on the client, or maintain an active count using some other means.

The second example query you listed ("people who own a pet whose name is "ABC") is possible through a collection group query against the subcollections named "pets" that filters documents using a field that contains the name of the pet. The query will return all of the pets among all of the subcollections, and you will have to iterate them and examine the references to those documents to build the list of people. With your data, it's not possible to issue a single query to get only the list of people.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • An alternative for the count use-case is to add a `pet_count` field to every user document, and keep that up to date either from the client or through Cloud Functions. You can then filter on that field. I'm pretty sure we answered something like that not too long ago, but I couldn't find it now. – Frank van Puffelen Feb 28 '20 at 20:56
  • @FrankvanPuffelen You mean this? https://stackoverflow.com/q/59924062/807126 – Doug Stevenson Feb 28 '20 at 21:04
  • 1
    I didn't, but that one is way better than what I was looking for. :) – Frank van Puffelen Feb 28 '20 at 21:58
  • @DougStevenson "The query will return all of the pets among all of the subcollections, and you will have to iterate them and examine the references to those documents to build the list of people" Is there a way to omit the extra iteration and examining for getting the people's IDs who have a pet named ABC? What do we need to change/add to the DB structure to easily get that info? – aytunch Mar 25 '20 at 12:20