登录
首页 >  Golang >  Go问答

如何将 BSON 文档转换为映射接口{}

来源:stackoverflow

时间:2024-04-20 19:09:51 265浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《如何将 BSON 文档转换为映射接口{}》,聊聊,我们一起来看看吧!

问题内容

我试图将光标的数据解码为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 中的键“applications”为空,但 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 类型上的内置接口将其转换为 map[string]接口{}

本篇关于《如何将 BSON 文档转换为映射接口{}》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>