Go 通过始终保持相同的顺序,将地图整理成BSON
我有一张地图,我用一段字符串创建它。然后,我想将其封送为bson格式,以作为索引插入mongodb。然而,由于地图是如何在Golang中创建的,我每次都会得到不同的索引顺序(有时是abc,有时是bac,cba…) 如何确保创建的封送索引始终以相同的顺序排列Go 通过始终保持相同的顺序,将地图整理成BSON,go,mongodb-indexes,Go,Mongodb Indexes,我有一张地图,我用一段字符串创建它。然后,我想将其封送为bson格式,以作为索引插入mongodb。然而,由于地图是如何在Golang中创建的,我每次都会得到不同的索引顺序(有时是abc,有时是bac,cba…) 如何确保创建的封送索引始终以相同的顺序排列 fields := ["a", "b", "c"] compoundIndex := make(map[string]int) for _, field := range fie
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
使用文档的有序表示形式:
.有打字错误吗?它应该是append(compoundex,bson.D)而不是append(compoundex,bson.E(将E改为D)?谢谢你回答我的问题:)@testing495这不是一个打字错误。
bson.D
是一个[]E
,一个有序的E
入口列表。有趣的是,我得到的是“E不是由包bsoncompiler未声明的导入名声明的”当我使用that@testing495答案假设bson
是该软件包的最新版本。您使用哪个软件包进行bson?啊,我使用go.mongodb.org/mongo-driver v1.4.6
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.