I’ve read into the collectionGroup
docs and have read this answer on getting collections from a specific document.
I’m looking for something similar, but where I list all of the sub collections that are referenced by documents within a specific collection.
For example, my ideal query would be something like db.collection('metrics').collectionGroup('days')
, where metrics
is the large collection that contains documents, each of which have a sub collection days
.
2
Answers
I am the author of the answer you linked. I looked into the guard that prevented me from expanding that answer to cover both documents and collections. It is unfortunately still in place as of
firebase
v9.17.1.As long as that guard remains in place, collection group queries may only search the whole database or be restricted to paths that fall under a particular document. A collection is not currently possible.
The workaround for this would be to nest the
metrics
collection under its own document. For the sake of efficiency, you will want to keep this collection ID and document ID as short as possible. In the example below, I have used ‘g’ as shorthand for ‘group’ and ‘1’ to indicate ‘group 1’ (could also use ‘m’ for metrics). Note: If you intend to have more than 10 such groups, start using01
,02
, etc. now, otherwise the below query will return invalid results.Which would allow you to then restrict paths to that group using:
You mentioned getting collections under a document. This is a sub collections and the query is something like
db.collection('metrics').document('x').collection('days')
from this reference you can query the documents in the
days
sub collection under documentx
db.collectionGroup('days')
this will query all documents in all days collections regardless of what document they are under.