Subhomoy Goswami
Subhomoy Goswami

Reputation: 195

Firestore: Does querying a collection also includes their sub collection?

I've a collection called users consisting their name and other personal details, and it also have a sub collection consisting of their vehicles.

But for some operation, I want to query only the user data. I'm afraid that it would include the sub collection also, which will increase my data usage.

The database structure is shown below:

enter image description here

db.collection("users").limit(10)
.get()
.then(function(querySnapshot) {     
  querySnapshot.forEach(function(doc) {
    console.log(doc.data());
     $scope.userList.push(doc.data());           
  });           
})
.catch(function(error) {
  console.log("Error getting documents: ", error);
});

I'm getting the data but i'm not sure whether this is the correct way of querying or not.

Upvotes: 14

Views: 5002

Answers (2)

SnorreDan
SnorreDan

Reputation: 2890

Firestore queries are shallow, meaning they only return the documents that are at the level you are querying for and they do not return their subcollections.

If you want to get the subcollections as well, you need to do a separate query for that.

Upvotes: 6

Alex Mamo
Alex Mamo

Reputation: 138824

Unlike in Firebase realtime database where to display a list of users you would have been downloaded the entire User object together with all children that exist within that object, in Cloud Firestore this is not an issue anymore. So if you have subcollections within a document, you will not download them.

Queries in Firestore are shallow: they only get items from the collection that the query is run against. There is no way to get documents from a top-level collection and other collections or subcollections in a single query. So don't worry about those subcollections.

Upvotes: 21

Related Questions