Skip to content
Advertisement

Get data from sub-collections in Firebase Firestore using nested query

I have following data structure in firestore:

  • flights [collection]
    • user1 [doc]
      • userFlights [sub collection]
        • flight 1
        • flight 2
        • flight 3
    • user2 [doc]
      • userFlights [sub collection]
        • flight 1
        • flight 2
        • flight 3

In order to read the data from all userFlights subcollections i use nested query as shown below.

My question: Would nested queries cause performance issues?

const userFlightRef = query(collection(db, "flights"));
const userUidDoc = await getDocs(userFlightRef);
userUidDoc.forEach(async userDoc => {
  const userFlightsQuery = query(collection(db, "flights/" + userDoc.id + "/userFlights"))
  const userFlights = await getDocs(userFlightsQuery);
  userFlights.forEach(flyer => {
     console.log(flyer.data());
  });
});

Thanks in advance

Advertisement

Answer

If you want to search all userFlights collections, you can use a collection group query.

You can get all documents from all userFlights collections with:

getDocs(collectionGroup(db, "userFlights"));
Advertisement