我有一个地图,它是我从一段字符串创建的。然后我想将其封送为bson格式,作为索引插入mongodb。但是,由于地图在Golang中的创建方式,我每次都会得到不同的索引顺序(有时是它的abc,有时是它的bac,cba...)。如何确保创建的封送索引始终按相同的顺序排列?fields := ["a", "b", "c"] compoundIndex := make(map[string]int)for _, field := range fields { compoundIndex[field] = 1}data, err := bson.Marshal(compoundIndex)fmt.Println(string(data)) // This output is always in a different order than the desired abc
1 回答

慕标琳琳
TA贡献1830条经验 获得超9个赞
使用文档 bson 的有序表示形式。D:
var compoundIndex bson.D
for _, field := range fields {
compoundIndex = append(compoundIndex, bson.E{Key: field, Value: 1})
}
data, err := bson.Marshal(compoundIndex)
fmt.Println(string(data)) // The elements are always printed in the same order.
在 Playground 上运行一个示例。
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消