如何将 JSON 字符串插入到 MongoDB 中?

huangapple go评论101阅读模式
英文:

How can I insert json string to MongoDB?

问题

你好!要将这个 JSON 字符串插入到 MongoDB 中,你需要将其转换为 BSON(Binary JSON)格式。在你的代码中,你可以使用 bson.M 类型来表示 BSON 文档。下面是修改后的代码示例:

import (
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "context"
    "fmt"
    "log"
    "time"
)

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")

    var data interface{}
    err = bson.UnmarshalExtJSON([]byte(json_value), true, &data)
    if err != nil {
        log.Fatal(err)
    }

    _, err = myCollection.InsertOne(ctx, data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Inserted successfully!")
}

在这个修改后的代码中,我们使用 bson.UnmarshalExtJSON 函数将 JSON 字符串转换为 BSON 文档,并将其插入到 MongoDB 中。请注意,我们将 json_value 参数传递给 bson.UnmarshalExtJSON 函数,而不是直接传递给 InsertOne 方法。

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

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: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)
}

How do I insert this json string to mongodb?

答案1

得分: 1

首先,添加一个ping来检查在defer client.Disconnect(ctx)之后连接是否成功。

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{}代替切片,如下所示:

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

v传递给InsertOne

注意:这是解决问题的一种方式。然而,推荐的做法是使用json和bson标签将JSON解析为go结构体,并将结构体实例传递给InsertOne

一些参考资料:

英文:

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:

答案2

得分: 0

insertOne()方法的语法如下:

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

你只需要执行以下操作:

myCollection.insertOne(json_metrics)
英文:

>The insertOne() method has the following syntax:

db.collection.insertOne(
   &lt;document&gt;,
   {
      writeConcern: &lt;document&gt; (optional)
   }
)

all you have to do is

myCollection.insertOne(json_metrics)

huangapple
  • 本文由 发表于 2022年11月1日 06:58:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/74269882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定