我有一個地圖,它是我從一段字符串創建的。然后我想將其封送為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 關注
- 99 瀏覽
添加回答
舉報
0/150
提交
取消