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

标签 mongodb go mongo-go

我尝试从我的 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已经可以按照您所介绍的那样工作。问题可能是您无法“轻松”获取 maxcnt 值。

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

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/

相关文章:

mongodb - 如何编码/解码 mongodb 游标?

mongodb map reduce 以按日期/日期获取唯一性

Golang 的 bool 类型

pointers - 指向具有保存类型的接口(interface)的指针

casting - Golang 转换多个返回值以匹配命名结果参数

mongodb - 如何在解码 MongoDB 文档时忽略空值?

mongodb - 无法启动 com.bitnami.mongodb

javascript - 为什么我的 bool 变量在路由中没有改变它们的值?

json - 来自 MongoDB 的日期打印为 "date":"2011-05-12T13:51:33Z"

mongodb - 使用 native 驱动程序附加到mongo查询