【问题标题】:How can I insert json string to MongoDB?如何将 json 字符串插入 MongoDB?
【发布时间】: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?

【问题讨论】:

    标签: json mongodb go


    【解决方案1】:

    insertOne() 方法具有以下语法:

    db.collection.insertOne(
       <document>,
       {
          writeConcern: <document> (optional)
       }
    )
    

    你所要做的就是

    myCollection.insertOne(json_metrics)
    

    【讨论】:

    • 当我只给 json_string 输入时,我得到以下错误: 1. 调用“myCollection.InsertOne”时参数不足 2. 不能使用“json_value”(类型字符串)作为类型(context.Context,interface{},*options .InsertOneOptions) 或 context.Context
    • 试试这个myCollection.insertOne(json_metrics)(小写的 i)
    • 不幸的是,错误仍然存​​在:未解决的参考 'insertOne'
    【解决方案2】:

    第一件事是:在defer client.Disconnect(ctx) 之后添加一个 ping 以检查连接是否成功。

    if err = client.Ping(ctx, readpref.Primary()); err != nil {
        log.Fatalf("ping failed: %v", err)
    }
    

    如果这不会引发错误,您可以按照stackoverflow: How to insert a json object array to mongodb in golang 中的说明解组您的 JSON 字符串。但是,在这种情况下,请使用 interface{} 而不是 slice,如下所示:

    var v interface{}
    if err := json.Unmarshal([]byte(json_value), &v); err != nil {
        log.Fatal(err)
    }
    

    v 传递给InsertOne

    注意:这是解决问题的一种方法。但是,推荐的解决方法是解组 JSON 以使用 json 和 bson 标签进入结构,并将结构实例传递给InsertOne

    一些参考资料:

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 2016-06-30
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2014-12-20
      相关资源
      最近更新 更多