如何在Golang中使用Firestore的NewAggregationQuery并转换聚合结果为整数
问题
我发现NewAggregationQuery是Firestore Query的一个方法,编写了如下查询代码:
q = fs.Collection("profiles").Where("age", "==", 18) res, err := q.NewAggregationQuery().WithCount("count").Get(context.Background()) fmt.Printf("res: %v of type %T\n", res, res)
运行后得到:
res: map[count:integer_value:5] of type firestore.AggregationResult
执行以下代码:
fmt.Printf("res: %v of type %T\n", res["count"], res["count"])
得到结果:
res: integer_value:5 of type *firestore.Value
但尝试使用res["count"].(*firestore.Value)时,出现编译错误:
compilation error, undefined: firestore.Value
请问如何将该结果转换为整数类型?
解决方法
你遇到的问题是因为*firestore.Value类型并未直接暴露在cloud.google.com/go/firestore包中,实际返回的是Firestore proto定义里的*firestorepb.Value类型(来自google.golang.org/genproto/googleapis/firestore/v1包),按以下步骤处理即可:
- 导入对应的proto包:
import firestorepb "google.golang.org/genproto/googleapis/firestore/v1"
- 对聚合结果做类型断言,再通过
GetIntegerValue()方法提取整数值:
val, ok := res["count"].(*firestorepb.Value) if !ok { // 处理类型断言失败的场景,比如结果类型不符合预期 log.Fatalf("failed to assert value to *firestorepb.Value") } count := val.GetIntegerValue() fmt.Printf("Total count: %d\n", count)
也可以用类型分支来处理,更灵活:
switch v := res["count"].(type) { case *firestorepb.Value: count := v.GetIntegerValue() fmt.Printf("Count: %d\n", count) default: fmt.Printf("Unexpected type: %T\n", v) }
内容的提问来源于stack exchange,提问作者Mquinteiro
相关产品推荐
相关产品推荐

