我有一个json字符串。像这样:
"{"http_requests":[{"http_requests":{"code":"400","method":"PUT","value":89}},{"http_requests":{"code":"200","method":"PUT","value":45}}]}"
我想把这个json插入mongodb。但是我的代码有错误。错误是";无法将类型字符串转换为BSON文档:WriteString只能在位于Element或Value上时进行写入,但位于TopLevel"上;
func insertJson(json_value string) {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://abc:123@cluster0.wrzj3zo.mongodb.net/?retryWrites=true&w=majority"))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
myDatabase := client.Database("my_db")
myCollection := myDatabase.Collection("my_collection")
myResult, err := myCollection.InsertOne(ctx, json_value)
if err != nil {
log.Fatal(err)
}
fmt.Println(myResult.InsertedID)
}
如何将这个json字符串插入mongodb?
首先:添加一个ping来检查defer client.Disconnect(ctx)
之后连接是否成功。
if err = client.Ping(ctx, readpref.Primary()); err != nil {
log.Fatalf("ping failed: %v", err)
}
如果这不会引发错误,您可以按照stackoverflow中的解释对JSON字符串进行解组:如何在golang中向mongodb插入JSON对象数组。然而,在这种情况下,使用interface{}
而不是切片,如下所示:
var v interface{}
if err := json.Unmarshal([]byte(json_value), &v); err != nil {
log.Fatal(err)
}
将v
传递到InsertOne
。
注意:这是解决问题的一种方法。然而,建议的方法是将JSON分解为带有JSON和bson标记的go结构,并将结构实例传递给
InsertOne
。
一些参考:
- 按示例:JSON
- 如何在MongoDB中使用Golang结构
- 使用结构标记
insertOne((方法具有以下语法:
db.collection.insertOne(
<document>,
{
writeConcern: <document> (optional)
}
)
你所要做的就是
myCollection.insertOne(json_metrics)