我尝试从我的 Go 代码中获取 MongoDB 集合的最大值。 我应该使用什么类型来解码结果?
当我使用bson.D{}
时如val2
输入结果如下 [{_id <nil>} {max 66} {cnt 14}]
.
代码如下:
filter := []bson.M{{
"$group": bson.M{
"_id": nil,
"max": bson.M{"$max": "$hellid"},
}},
}
cursor, err := collection.Aggregate(ctx, filter)
for cursor.Next(ctx) {
val2 := ???
err := cursor.Decode(&val2)
fmt.Printf("cursor: %v, value: %v\n", cursor.Current, val2)
}
}
最佳答案
使用bson.D
已经可以按照您所介绍的那样工作。问题可能是您无法“轻松”获取 max
和 cnt
值。
使用如下结构对结果文档进行建模:
type result struct {
Max int `bson:"max"`
Count int `bson:"cnt"
}
虽然 cnt
不是由您提供的示例代码生成的。
然后:
var res result
err := cursor.Decode(&res)
关于mongodb - 将 MongoDB $max 结果转换为 golang 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58392811/