1

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

当我使用bson.D{}asval2类型时,结果看起来像[{_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)
    }
}
4

1 回答 1

1

正如您所介绍的那样,使用bson.D已经有效。问题可能是您不能“轻松”地找出maxandcnt值。

使用如下结构对结果文档进行建模:

type result struct {
    Max   int `bson:"max"`
    Count int `bson:"cnt"
}

虽然cnt不是由您提供的示例代码产生的。

接着:

var res result
err := cursor.Decode(&res)
于 2019-10-15T10:54:31.217 回答