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

时间:2019-01-10 17:12:12

标签: mongodb go mongo-go

我试图将光标的数据解码为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”)应用程序:bson.Array [bson.Document {bson.Element {“ enabled”:true}}] userName:coto userUUID:df2d ea92-c189-53b3-aafe-485d0be23bee]

然后将地图解析为JSON:

{“ _ id”:“ 5c2d0809a49bad7d547ec028”,“应用程序”:[{}],“ userName”:“ coto”,“ userUUID”:“ df2dea92-c189-53b3-aafe-485d0be23bee”}

您可以看到JSON中的关键“应用程序”为空,但BSON文档中确实包含该内容。我不知道为什么数据消失了。

如何解决此错误? 谢谢。

3 个答案:

答案 0 :(得分:2)

已解决:

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

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)

    if err != nil {
        report.Report{Error: err, Trace: report.Trace()}.Send()
        requestContext.StatusCode(500)
        return `500 Internal server error`
    }

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

    if err != nil {
        report.Report{Error: err, Trace: report.Trace()}.Send()
        requestContext.StatusCode(500)
        return `500 Internal server error`
    }

    err = json.Unmarshal(temporaryBytes, &jsonDocument)

    if err != nil {
        report.Report{Error: err, Trace: report.Trace()}.Send()
        requestContext.StatusCode(500)
        return `500 Internal server error`
    }

    jsonDocuments = append(jsonDocuments, jsonDocument)
}

答案 1 :(得分:0)

来自mongo-go-driver的bson.Mpimitive.M的类型。如果没有看到声明的变量,就很难说出出了什么问题。这是使用官方的mongo-go-driver的有效示例。

map[string]interface{}

func TestUnmarshal(t *testing.T) { uri := "mongodb://localhost/stackoverflow?replicaSet=replset" ctx := context.Background() client, err := mongo.Connect(ctx, uri) if err != nil { t.Fatal(err) } c := client.Database("stackoverflow").Collection("acoll") list := []bson.M{bson.M{"enabled": true}} id := primitive.NewObjectID() c.InsertOne(ctx, bson.M{"_id": id, "applications": list, "userName": "my name"}) var itemBson bson.M var itemMap map[string]interface{} cur, _ := c.Find(ctx, bson.M{}) for cur.Next(ctx) { cur.Decode(&itemBson) t.Log(itemBson) b, _ := bson.Marshal(itemBson) bson.Unmarshal(b, &itemMap) t.Log(itemMap) } }

的输出
go test

答案 2 :(得分:0)

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{}