Ask Your Question
3

How to search for data in a subcollection of Firestore using a field from the main document?

asked 2023-02-25 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-06-29 23:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-25 11:00:00 +0000

Seen: 12 times

Last updated: Jun 29 '21