登录
首页 >  Golang >  Go问答

如何从 MongoDB 获取数据并将其作为 Golang 中的 JSON 发送到 API

来源:stackoverflow

时间:2024-04-22 17:42:35 357浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《如何从 MongoDB 获取数据并将其作为 Golang 中的 JSON 发送到 API》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在工作中编写一个 golang api,当调用该 api 时,它会从两个不同的 mongodb 集合获取数据并将其附加到结构中,将其转换为 json,然后进行字符串化并发送到 api (amazon sqs)

问题是,定义从 mongodb 接收的数据的结构,虽然有些字段定义正确,但有些字段不同

// IncentiveRule struct defines the structure of Incentive rule from Mongo
type IncentiveRule struct {
    ... Other vars
    Rule               Rule               `bson:"rule" json:"rule"`
    ... Other vars
}

// Rule defines the struct for Rule Object inside an incentive rule
type Rule struct {
    ...
    Rules          interface{}    `bson:"rules" json:"rules"`
    RuleFilter     RuleFilter     `bson:"rule_filter" bson:"rule_filter"`
    ...
}

// RuleFilter ...
type RuleFilter struct {
    Condition string        `bson:"condition" json:"condition"`
    Rules     []interface{} `bson:"rules" json:"rules"`
}

虽然这有效,但 rule 结构中定义的 interface{} 有所不同,并且在获取为 bson 并解码并重新编码为 json 时,而不是编码为 json 中的 "fookey":"barvalue" ,它是编码为 "key":"fookey","value":"barvalue",如何避免这种行为并将其设置为 "fookey":"barvalue"


解决方案


如果您使用 interface{},mongo-go 驱动程序可以自由选择它认为适合表示结果的任何实现。通常它会选择 bson.D 来表示文档,该文档是键值对的有序列表,其中键值对是一个具有 Key 字段和 Value 字段的结构体,因此 Go 值可以保留字段顺序。

如果字段顺序不是必需的/重要的,您可以显式使用 bson.M 代替 interface{}[]bson.M 代替 []interface{}bson.M是一个无序映射,但是它以fieldName:fieldValue的形式表示字段,这正是你想要的。

今天关于《如何从 MongoDB 获取数据并将其作为 Golang 中的 JSON 发送到 API》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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