将MongoDB$max结果转换为golang数据

将MongoDB$max结果转换为golang数据,mongodb,go,mongo-go,Mongodb,Go,Mongo Go,我尝试从我的Go代码中获取MongoDB集合的最大值。 我应该使用什么类型来解码结果 当我使用bson.D{}作为val2类型时,结果看起来像[{{u id}{max 66}{cnt 14}] 代码如下: filter := []bson.M{{ "$group": bson.M{ "_id": nil, "max": bson.M{"$max": "$hellid"}, }}, } cur

我尝试从我的Go代码中获取MongoDB集合的最大值。 我应该使用什么类型来解码结果

当我使用
bson.D{}
作为
val2
类型时,结果看起来像
[{{u id}{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)

我根本不需要
\u id
。非常感谢(尽管这是禁止的:)