skip to Main Content

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


  1. 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 using 01, 02, etc. now, otherwise the below query will return invalid results.

    "/g": {
      "/1": {
        "/metrics": {
          "/docA": {
            "/days": { /* ... */ }
          },
          "/docB": {
            "/days": { /* ... */ }
          },
          "/docC": {
            "/days": { /* ... */ }
          }
        }
      }
    }
    

    Which would allow you to then restrict paths to that group using:

    // note: legacy syntax
    firebase.firestore().collectionGroup('days')
      .orderBy(firebase.firestore.FieldPath.documentId())
      .startAt("g/1"),
      .endAt("g/1uf8ff")
      .get()
      .then((querySnapshot) => {
        console.log("Found " + querySnapshot.size + " docs");
        querySnapshot.forEach((doc) => console.log("> " + doc.ref.path))
      })
      .catch((err) => {
        console.error("Failed to execute query", err);
      })
    
    Login or Signup to reply.
  2. 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 document x

    db.collectionGroup('days')

    this will query all documents in all days collections regardless of what document they are under.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search