登录
首页 >  Golang >  Go问答

Golang中游标迭代时如何从mongodb记录中提取字段

来源:stackoverflow

时间:2024-04-13 20:00:32 337浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang中游标迭代时如何从mongodb记录中提取字段》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我对 golang 编程和 mongodb 接口相当陌生。

我有一个由另一个应用程序创建的记录数据库。我正在尝试遍历数据库并检查每条记录的特定字段。我可以将完整记录解码为 bson,但无法获取具体值。

这个结构定义了我想要提取的 3 个字段:

type mydbaserec struct {
    aid        string  `bson:"pon-util-aid"`
    ingresspct string  `bson:"ingress-bucket-percent"`
    egresspct  string  `bson:"egress-bucket-percent"`
}

这是我的代码,用于在集合后迭代光标。find(ctx, queryfilter) 并将结果解码为 bson 和我的结构:

    var myresult mydbaserec
    var bsonmresult bson.m

    var count int
    for cursor.next(ctx) {

        err := cursor.decode(&myresult)
        if err != nil {
            fmt.println("cursor.next() error:", err)
            panic(err)
            // if there are no cursor.decode errors
        } else {
            fmt.println("\nresult type:", reflect.typeof(myresult))
            fmt.printf("result: %+v\n", myresult)

        }

        err = cursor.decode(&bsonmresult)
        if err != nil {
            fmt.println("bson decode error:", err)
            panic(err)
            // if there are no cursor.decode errors
        } else {
            fmt.println("\nresult type:", reflect.typeof(bsonmresult))
            fmt.println("\nresult:", bsonmresult)
        }

    }

下面是循环一次迭代的示例。 bson 解码似乎可以工作,但我的结构是空的:

result type: internal.mydbaserec
result: {aid: ingresspct: egresspct:}

result type: primitive.m

result: map[pon-util-aid:rolt-1-montreal/1/1/xp2 _id:objectid("5d70b4d1b3605301ef72228b") 
admitted-assured-upstream-bw:0 admitted-excess-upstream-bw:0 admitted-fixed-upstream-bw:0 
assured-upstream-bytes:0 available-excess-upstream-bw:0 available-fixed-upstream-bw:622080 
app_counters_key_field:rolt-1-montreal/1/1/xp2 app_export_time:1567665626 downstream-octets:52639862633214 
egress-bucket-bps:8940390198 egress-bucket-percent:91 egress-bucket-seconds:559 
excess-upstream-bytes:0 fixed-upstream-bytes:0 ingress-bucket-bps:8253153852 
ingress-bucket-percent:84 ingress-bucket-seconds:559 sample-time:0 upstream-octets:48549268162714]

我本来希望得到

result: {aid:"ROLT-1-MONTREAL/1/1/xp2" ingressPct:84 egressPct:91}

关于如何从每条记录中正确查找这 3 个字段有什么建议吗?

===更新:下面的第一条评论回答了我的问题。


解决方案


首先,在 go 中,仅导出以 (unicode) 大写字母开头的字段。另请参阅 Exported identifiers。默认解码器将尝试仅解码导出的字段。所以你应该将结构更改为:

type myDbaseRec struct {
    Aid        string  `bson:"pon-util-aid"`
    IngressPct int32  `bson:"ingress-bucket-percent"`
    EgressPct  int32  `bson:"egress-bucket-percent"`
}

另请注意,上面的 ingresspctegresspct 结构的类型为 int32。这是因为文档中的值以数字(int/double)表示,而不是字符串。您可以相应地将其更改为其他数字类型,即 int16、int64 等。

以上就是《Golang中游标迭代时如何从mongodb记录中提取字段》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>