5

我试图将光标的数据解码为map[string]interface{},我直接尝试了但它根本不起作用,所以我发现我必须将它转换为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"}

如您所见,关键的“应用程序”在 JSON 中是空的,但在 BSON 文档中确实有内容。我不知道为什么数据会消失。

我该如何解决这个错误?谢谢。

4

2 回答 2

10

解决了:

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

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)
}
于 2019-01-14T18:28:42.037 回答
1
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将其转换为map[string]interface{}

于 2020-08-18T20:50:52.207 回答