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

How to get data as is from MongoDB and send it to an API as JSON in Golang

我正在写一个 Golang 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 时,而不是编码为 [=16] =] 在 JSON 中,它被编码为 "Key":"fookey","Value":"barvalue",如何避免这种行为并将其编码为 "fookey":"barvalue"

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

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