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

如何按原样从MongoDB获取数据,并将其作为Golang中的JSON发送到API,json,mongodb,go,struct,bson,Json,Mongodb,Go,Struct,Bson,我正在编写一个Golang API,当调用它时,它从两个不同的MongoDB集合获取数据,并将其附加到一个结构中,将其转换为JSON,然后字符串化并发送到一个API(Amazon SQS) 问题是,定义从MongoDB接收的数据的结构,虽然有些字段定义正确,但有些字段是可变的 // IncentiveRule struct defines the structure of Incentive rule from Mongo type IncentiveRule struct { ...

我正在编写一个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"`
}


尽管如此,在
规则
结构中定义的
接口{}
是变化的,当作为BSON并解码和重新编码为JSON时,它不是编码为
“fookey”:“barvalue”
,而是编码为
“Key”:“fookey”,“Value”:“barvalue”
,如何避免这种行为并将其作为
“fookey”:“barvalue”

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


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

使用
bson.M
代替
interface{}
,使用
[]bson.M
代替
[]interface{}
。这解决了您的问题吗?这解决了我的问题。非常感谢,请将其作为答案发布,以便我可以将其标记为解决方案