我如何将 BSON 文档转换为 map[string]interface{}

How I convert a BSON Document into a map[string]interface{}

我试图将游标的数据解码成一个映射[string]接口{},我直接试了但是根本不起作用,所以我发现我必须将它转换为BSON 文档,然后将其转换为 map[string]interface{},最后转换为 JSON 字符串。我尝试了以下代码:

...
for cursor.Next(context.Background()) {
    err = cursor.Decode(&itemBson)
    ...
    b, err := bson.Marshal(itemBson)
    ...
    err = bson.Unmarshal(b, &itemMap)
    ...
}
...

但是bson文档有如下值:

map[_id:ObjectID("5c2d0809a49bad7d547ec028") applications:bson.Array[bson.Document{bson.Element{"enabled": true}}] userName:coto userUUID:df2d ea92-c189-53b3-aafe-485d0be23bee]

地图解析为JSON:

{"_id":"5c2d0809a49bad7d547ec028","applications":[{}],"userName":"coto","userUUID":"df2dea92-c189-53b3-aafe-485d0be23bee"}

可以看到"applications"键在JSON中是空的,但在BSON文档中确实有内容。不知道为什么数据不见了

如何解决这个错误? 谢谢

已解决:

我使用以下代码解决了这个错误:

var jsonDocuments []map[string]interface{}
var byteDocuments []byte

var bsonDocument bson.D
var jsonDocument map[string]interface{}
var temporaryBytes []byte

for cursor.Next(context.Background()) {
    err = cursor.Decode(&bsonDocument)

    ...

    temporaryBytes, err = bson.MarshalExtJSON(bsonDocument, true, true)

    ...

    err = json.Unmarshal(temporaryBytes, &jsonDocument)

    ...

    jsonDocuments = append(jsonDocuments, jsonDocument)
}
temp := itemBson.data.(primitive.D) // convert interface to primitive D

metadata := temp.Map() // map to map[string]interface{}

if v, ok := metadata[prqKey]; ok { // check and use value
    commitID = v.(string)
}

您可以在 primitive.D 类型上使用 built-in 接口将其转换为 map[string]interface{}