Cloud Firestore collection count

后端 未结 17 1314
庸人自扰
庸人自扰 2020-11-22 09:25

Is it possible to count how many items a collection has using the new Firebase database, Cloud Firestore?

If so, how do I do that?

17条回答
  •  不思量自难忘°
    2020-11-22 09:37

    No, there is no built-in support for aggregation queries right now. However there are a few things you could do.

    The first is documented here. You can use transactions or cloud functions to maintain aggregate information:

    This example shows how to use a function to keep track of the number of ratings in a subcollection, as well as the average rating.

    exports.aggregateRatings = firestore
      .document('restaurants/{restId}/ratings/{ratingId}')
      .onWrite(event => {
        // Get value of the newly added rating
        var ratingVal = event.data.get('rating');
    
        // Get a reference to the restaurant
        var restRef = db.collection('restaurants').document(event.params.restId);
    
        // Update aggregations in a transaction
        return db.transaction(transaction => {
          return transaction.get(restRef).then(restDoc => {
            // Compute new number of ratings
            var newNumRatings = restDoc.data('numRatings') + 1;
    
            // Compute new average rating
            var oldRatingTotal = restDoc.data('avgRating') * restDoc.data('numRatings');
            var newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;
    
            // Update restaurant info
            return transaction.update(restRef, {
              avgRating: newAvgRating,
              numRatings: newNumRatings
            });
          });
        });
    });
    

    The solution that jbb mentioned is also useful if you only want to count documents infrequently. Make sure to use the select() statement to avoid downloading all of each document (that's a lot of bandwidth when you only need a count). select() is only available in the server SDKs for now so that solution won't work in a mobile app.

提交回复
热议问题