Document1がブログ投稿であり、サブコレクションがコメントであると仮定しよう。
- コメントdoc createで関数をトリガーします。
- 親ドキュメントを読み取り、既存のカウントをインクリメントします。
- 親ドキュメントにデータを書き込みます。
注:お使いのカウント値が速く、一度毎秒よりも変化した場合、あなたはhttps://firebase.google.com/docs/firestore/solutions/counters
exports.aggregateComments = functions.firestore
.document('posts/{postId}/comments/{commentId}')
.onCreate(event => {
const commentId = event.params.commentId;
const postId = event.params.postId;
// ref to the parent document
const docRef = admin.firestore().collection('posts').doc(postId)
return docRef.get().then(snap => {
// get the total comment count and add one
const commentCount = snap.data().commentCount + 1;
const data = { commentCount }
// run update
return docRef.update(data)
})
});
分散カウンタを必要とするかもしれないあなたは、高度な集計計算を実行する必要がある場合、私は、詳細なfirestore aggregation exampleをまとめます簡単な数を超えて
[Cloud Firestoreでコレクション内のドキュメント数を取得する方法](https://stackoverflow.com/questions/46553314/how-to-get-a-count-of-number-クラウド・ファイアストアを備えたコレクション・オブ・ア・コレクション・オブ・クラウド・ファイアストア) –