I have a firebase database with a collection called lines. I'm trying to get the total count of line records. I initially tried this:
const count = firestore.collection('lines').get().then(snapshot => snapshot.docs.length);
...but this forces firebase to read all the line records.
I'm wondering if there's a quicker, less expensive way to get the record count.
I tried this:
const count = firestore.collection('lines').count();
This gives me this object:
{
"_query":{
"_firestore":{
"projectId":"xxx-12345"
},
"_queryOptions":{
"parentPath":{
"segments":[
]
},
"collectionId":"lines",
"converter":{
},
"allDescendants":false,
"fieldFilters":[
],
"fieldOrders":[
],
"kindless":false,
"requireConsistency":true
},
"_serializer":{
"allowUndefined":false
},
"_allowUndefined":false
},
"_aggregates":{
"count":{
}
}
}
...but I don't see the count anyway in here (except for count
but it's an empty object).
What is the best way to get the record count from a firebase collection with as few reads as possible?
Thanks!
Like all Firebase query methods, the count method is asynchronous and returns a promise that becomes resolved when the query is finished. You need to await the promise in order to get the count value. See the example in the documentation (assuming you are using the Firebase Admin SDK), and note the use of the await
keyword:
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
If you prefer to use then
instead of await
, you can do that as well, as you are with the other query you showed.