skip to Main Content

I have a json string. Like this:

"{"http_requests":[{"http_requests":{"code":"400","method":"PUT","value":89}},{"http_requests":{"code":"200","method":"PUT","value":45}}]}"

I want to insert this json to mongodb. But I have error in my code.
The error is "cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel"

func insertJson(json_value string) {
   client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://abc:[email protected]/?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)
}

How do I insert this json string to mongodb?

2

Answers


  1. The insertOne() method has the following syntax:

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

    all you have to do is

    myCollection.insertOne(json_metrics)
    
    Login or Signup to reply.
  2. First thing’s first: Add a ping to check if connection is succeeding after defer client.Disconnect(ctx).

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

    If that doesn’t throw an error, you can unmarshal your JSON string as explained in stackoverflow: How to insert a json object array to mongodb in golang. However, in this case, use interface{} instead of slice as follows:

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

    Pass v to InsertOne.

    Note: This is one way of solving the problem. However, the recommended way to go about it is to unmarshal the JSON to go struct with json and bson tags, and pass the struct instance(s) to InsertOne.

    Some references:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search