英文:
Marshall a Map into BSON by always retaining the same order
问题
我有一个地图,它是由一个字符串切片创建的。然后,我想将其编组为bson格式,以便将其作为索引插入到mongodb中。然而,由于在Golang中创建地图的方式,每次都会得到不同顺序的索引(有时是abc,有时是bac,cba...)。
如何确保创建的编组索引始终按相同的顺序?
fields := []string{"a", "b", "c"}
compoundIndex := make(map[string]int)
for _, field := range fields {
compoundIndex[field] = 1
}
data, err := bson.Marshal(compoundIndex)
fmt.Println(string(data)) // 此输出总是与期望的abc顺序不同
英文:
I have a map, which I create from a slice of strings. I then want to marshal this into bson format, to insert into mongodb as an index. However, because of how maps are created in Golang, I get a different ordering of the index each time (sometimes its abc, othertimes its bac, cba...).
How can I ensure that the marshalled index created is always in the same order?
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
得分: 2
使用有序的文档表示,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)) // 元素总是以相同的顺序打印。
英文:
Use an ordered representation of a document, 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论