Cloud Firestore collection count

后端 未结 17 1308
庸人自扰
庸人自扰 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:49

    Increment a counter using admin.firestore.FieldValue.increment:

    exports.onInstanceCreate = functions.firestore.document('projects/{projectId}/instances/{instanceId}')
      .onCreate((snap, context) =>
        db.collection('projects').doc(context.params.projectId).update({
          instanceCount: admin.firestore.FieldValue.increment(1),
        })
      );
    
    exports.onInstanceDelete = functions.firestore.document('projects/{projectId}/instances/{instanceId}')
      .onDelete((snap, context) =>
        db.collection('projects').doc(context.params.projectId).update({
          instanceCount: admin.firestore.FieldValue.increment(-1),
        })
      );
    

    In this example we increment an instanceCount field in the project each time a document is added to the instances sub collection. If the field doesn't exist yet it will be created and incremented to 1.

    The incrementation is transactional internally but you should use a distributed counter if you need to increment more frequently than every 1 second.

    It's often preferable to implement onCreate and onDelete rather than onWrite as you will call onWrite for updates which means you are spending more money on unnecessary function invocations (if you update the docs in your collection).

提交回复
热议问题