通过始终保留相同的顺序将映射编入 BSON

我有一个地图,它是我从一段字符串创建的。然后我想将其封送为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



ABOUTYOU
浏览 87回答 1
1回答

慕标琳琳

使用文档 bson 的有序表示形式。D:var compoundIndex bson.Dfor _, 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 上运行一个示例。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go