简体   繁体   中英

Most efficient approach to count documents in one or more Firestore collection(s)

I'm developing a delivery application, I would like to get the counts for the admin to analyze (number of orders, number orders paid with visa, etc...). I tried to read all the documents and get snapshot count but I figured out it will cost me a lot of reads and if the dataset is large it will slow down my application. So I created a collection called counts, and I created a cloud function to listen for document create and increment the count field in users document in the counts' collection, it works perfectly but I would like to know if it will cost me a fortune and if there is a better solution. note: I will listen to 5+ collections

here is my function:

const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

    var firestore = admin.firestore();
 // Listens for any document created in the users collection
exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {
 firestore.collection('counts').doc('users').update({ count: admin.firestore.FieldValue.increment(1) })
return 'done';
});

I created a cloud function to listen for document create and increment the count field in users document in the counts' collection.

This is indeed one of the best solution for your requirement. Note that if the frequency of write to the "main collections" (ie the 5+ collections) is so high that the counter document may be updated more that once per second, you may use a set of distributed counters .

I would like to know if it will cost me a fortune

Each time you create a document, the cost for updating the counter corresponds to one Firestore write and one Cloud Function invocation (and potentially some Outbound networking cost depending on where are located your Firestore database and your Cloud Function, see here and here ). Will it cost "a fortune"? It all depends on the number of documents created in the "main collections" AND the number of times you want to read these counters.

If you read these counters once a year , it may be more affordable to query all the documents of the 5 collections. But if you read it once a day or once a week and those collections have "a lot of documents", it will probably be more affordable to use a Cloud Function as you are doing. It's up to you to do the math in order to evaluate the preferred approach, based on some figures that you are the only one to know (or the only one being able to estimate).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM