将一个 Map 转换为 BSON,并始终保持相同的顺序。

huangapple go评论97阅读模式
英文:

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)) // 元素总是以相同的顺序打印。

在 Playground 上运行示例

英文:

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.

Run an example on the Playground.

huangapple
  • 本文由 发表于 2021年5月20日 22:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/67622678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定