0
votes

A compound query that searches all Documents in a Collection works perfectly, as below:

var newData = admin.firestore().collection("MyProject").where('username', '==', 'myname');

In order to store more user generated data, I'm using "collection/doc/collection/doc" functionality where the docs are auto generated based on users' inputs.

Now to query data where anything is created in the last document, I want something like this:

var newData = admin.firestore().collection("MyProject/{docID}/subcollection")
.where('location', '==', 'location');

But this isn't working. Is there something else that I can try which would get me the results of matching content only?

(nor did the below)

var newData = admin.firestore().collection("MyProject".doc({docID}").collection("subcollection")
    .where('location', '==', 'location');

Perhaps wildcards only work with Triggers and not queries? (https://firebase.google.com/docs/functions/firestore-events). I'm not sure as I couldn't any more documentation on web on this. Without this feature, I find collection/doc/collection/doc... style of storage quite limiting and useless.

One workaround I have thought of is fetching "all" the documents in MyCollection and run the query 'forEach' of those Documents. This would have higher complexity and more reads in Firestore, as there could be thousands of documents in MyProject.

Please share your wisdom on how to fetch data with least complexity. Thank you in advance!

edenter image description here

1

1 Answers

1
votes

Firestore queries do not support wildcards. You have to know the IDs of the collections and documents in the path to the final collection you want to query. The wildcards you see for Cloud Functions triggers are an entirely different thing, as they are not actually performing any query at all.

If organizing documents into subcollections is making it more difficult for you to query your data, then don't use it. You should always model your data in such a way that it best satisfies the queries you need to perform. Sometimes a more flat model allows for more flexible querying, and that's fine. Firestore has no problems scaling billions of documents in a subcollection.

You might also want to look into collection group queries if that makes it easier to query all subcollections with the same name, no matter where they're organized. This might work for you:

admin.firestore()
    .collectionGroup("subcollection")
    .where('location', '==', 'location');