【发布时间】:2022-11-01 12:22:08
【问题描述】:
我有一个 json 字符串。像这样:
"{"http_requests":[{"http_requests":{"code":"400","method":"PUT","value":89}},{"http_requests":{"code":"200","method":"PUT","value":45}}]}"
我想将此json插入到mongodb。但是我的代码中有错误。 错误是“无法将类型字符串转换为 BSON 文档:WriteString 只能在定位在元素或值上但定位在 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?
【问题讨论】: