Typescript云函数聚合firestore字段值



我有一个文档,我有两个字段;

<<ol>
  • 类别/gh>
  • 持续时间(微毫秒)
  • Category可以有多个值,如category1, category2等

    我想计算category == category1的所有文档的持续时间之和。请帮忙查询。

    import * as admin from 'firebase-admin'
    import * as functions from 'firebase-functions'
    
    admin.initializeApp()
    export const updateCharts = 
    functions.firestore.document('users/{UserId}/count/{uid}')
    .onWrite(async(change, _) => await updateStats(change))
    async function updateStats (change: 
    functions.Change<functions.firestore.DocumentSnapshot>){
    const chartRating = change.after.ref.parent
    let title = (await chartRating.where('Title', '==', 'Game').get()).size;
    //duration
    const restaurantRef = chartRating.parent!
    console.log('{restaurantRef.path} now has ${Title}')
    await restaurantRef.update({
    Title: Title,
    })
    

    使用查询获取所有文档后,您可以使用reduce()查找总持续时间:

    let title = await chartRating.where('Title', '==', 'Game').get();
    const totalDuration = title.docs.reduce((a, b) => a + b.data()["duration"], 0)
    // Adds 'duration' field of all documents
    

    一个更便宜的替代方法是从restaurantRef中读取以前的total,减去该文档持续时间的旧值并添加更新的值。这将只花费1次读和1次写操作,而读取所有文档将花费N次读取,其中N是匹配的文档数。

    最新更新