【问题标题】:Marshall a Map into BSON by always retaining the same order通过始终保持相同的顺序将 Map 编入 BSON
【发布时间】:2021-05-20 14:43:48
【问题描述】:

我有一张地图,它是从一段字符串中创建的。然后我想将它编组为 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

【问题讨论】:

    标签: go mongodb-indexes


    【解决方案1】:

    使用文档的有序表示,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.

    【讨论】:

    • 有错字吗?应该是 append(compoundIndex, bson.D 而不是 append(compoundIndex, bson.E (将 E 更改为 D)?感谢您回答我的问题 :)
    • @testing495 这不是错字。 bson.D[]EEntries 的有序列表。
    • 有趣的是,当我使用它时,我得到“E 未由包 bsoncompilerUndeclaredImportedName 声明”
    • @testing495 答案假定bson 是包go.mongodb.org/mongo-driver/bson 的最新版本。 bson 你用的是哪个包?
    • 啊我使用 go.mongodb.org/mongo-driver v1.4.6
    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 2020-11-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多