通过始终保持相同的顺序将 Map 编组到 BSON
Marshall a Map into BSON by always retaining the same order
我有一张地图,它是根据一段字符串创建的。然后我想将其编组为 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
使用文档的有序表示,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.
我有一张地图,它是根据一段字符串创建的。然后我想将其编组为 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
使用文档的有序表示,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.