13

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Subhomoy Goswami
  • 185
  • 2
  • 10

2 Answers2

20

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • So it means that you won't be charged for "reading" the subcollection (in his example, `vehicles` when i query the document, right?). Because from what I know in firestore, when you query the document, you essentially grab everything from that document. – Gabriel Apr 18 '20 at 03:38
  • 1
    @Max Yes, that's right. You grab everything (all fields) except the subcollections. – Alex Mamo Apr 18 '20 at 11:02
5

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.

craft
  • 2,017
  • 1
  • 21
  • 30
SnorreDan
  • 2,740
  • 1
  • 14
  • 17