Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To search for data in a subcollection of Firestore using a field from the main document, you can use a collection group query. A collection group query allows you to query across all collections with the same name, including subcollections.

Here's an example:

const mainCollectionRef = firestore.collection("mainCollection");
const query = mainCollectionRef.where("field1", "==", "value1");

// Perform a collection group query on the subcollection "subCollection"
const subCollectionQuery = firestore.collectionGroup("subCollection").where("field2", "==", "value2");

// Chain the main collection query with the subcollection query
query.get().then((mainDocs) => {
  mainDocs.forEach((doc) => {
    const mainDocId = doc.id;
    subCollectionQuery.get().then((subDocs) => {
      subDocs.forEach((subDoc) => {
        // Do something with the subdocument
      });
    });
  });
});

In this example, we first perform a query on the main collection to retrieve all documents where "field1" equals "value1". We then chain this query with a collection group query on the "subCollection" subcollection to retrieve all documents where "field2" equals "value2".

Note that you may need to structure your data differently in order to make use of collection group queries. For example, instead of storing subcollection documents within the main collection document, you could create a separate collection for the subcollection documents and use a field to link them to the main document.