Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestoreaggregate

Firestore ".count()" returning incorrect value


I am running a query on my STAGING instance of Firestore, where the collection is small enough that I know I have about 140 document IDs.

The query:

const my_coll_count = await app.firestore()
  .collection('my_collection')
  .count()
  .get()
  .then(s => s.data().count);

The result returns a count of 18 documents, instead of 140.

Similarly, when I go to the database in Google Cloud Console's Firestore, the bottom total there reads 18 documents. This also makes no sense to me, as it does not compare at all with what I see for the same collection when I view it from the Firebase Console.

Yet, when I am looping through this same collection with a couple of "where" clauses to add data, it happily updates 122 documents. Whaaaaattttt is goingggggg onnnnnn?!

Is there any reason that I cannot receive an accurate total of all of the ids in this collection?

My own best guess is it might have to do with the fact that the collection is comprised mostly of ids, without any data fields, but I feel like that shouldn't exclude them from being counted. Most of the documents have a sub-collection, that should count for something, shouldn't it?

UPDATE: It's true! Only records that actually have documents are getting counted. It will also count documents that are just an empty object {}, but it won't count them if they are truly null. However, these IDs all have a sub-collection. Is there a decent way I can get a count of all of the ids, even if they do not have a document attached to them?


Solution

  • The result returns a count of 18 documents, instead of 140.

    The documents with no fields are displayed in the Firebase Console in italics. So the Firebase Console is telling you that those documents don't exist. What you did do, was only to create a sub-collection under a document that never existed. In other words, you have just reserved an ID for a document in the collection and then created a sub-collection under it. Bear in mind that creating a sub-collection under a document ID will not automatically create that document.

    The document in italics represents just a placeholder that lets you navigate further into sub-collections. The documents without fields can not be queried, can not be counted nor can be deleted. If you don't want to see such documents in the Firebase Console, you will have to delete all documents of their sub-collections in order to see them removed.

    Remember that in Firestore documents and sub-collections don't work like filesystem files and directories. Sub-collections are not tied in any way to a parent document.