如何在 golang 中将 json 对象数组插入到 mongodb

How to insert a json object array to mongodb in golang

我的 json 如下所示,

[
  {
    "key1": 1,
    "key2": "val2"
  },
  {
    "key1": 2,
    "key2": "val2"
  }
]

这个 json 以字符串格式出现,我希望 json 数组中的对象作为单独的记录插入 mongodb 中。我提到了 https://labix.org/mgo 但无法找到关于上述用例的足够示例。感谢您在寻找解决方案时的想法。

Unmarshal the JSON to []interface{} and insert the result in the database. Assuming that c is an mgo.Collectiondata是一个包含JSON值的[]字节,使用如下代码:

var v []interface{}
if err := json.Unmarshal(data, &v); err != nil {
   // handle error
}
if err := c.Insert(v...); err != nil {
   // handle error
}

如果您已经有 json 数据,请从第 2 步开始。

如果您有 Xml 数据,您需要先使用此包 ("github.com/basgys/goxml2json")

转换为 json 格式
 type JsonFileResponse struct {
    JsonData string        `bson:"JsonData " json:"JsonData"`
}

step 1: jsonData, err := xml2json.Convert(xml)
        if err != nil {
            panic("getting error while converting xml to json",err)
        }

step 2: session need to open by using your mongodb credentials.

    collection := session.DB("database name").C("Collection Name")
    err = collection.Insert(JsonFileResponse{JsonData :json.String()})
    if err != nil {
        log.Fatal(err)
    } 

在这个例子中我将存储混合数组

test_string := '[[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"\"x","[y","'z",[[1,2,3],[1,2,3]]]]'

在 mongodb 内作为 json:

{datum: [[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"\"x","[y","'z",[[1,2,3],[1,2,3]]]]}

package main

import (
    "strings"
    "context"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
)



type datum2 struct {
    Datum interface{} `json:datum`
}





var userCollection = db().Database("goTest").Collection("users") // get collection "users" from db() which returns *mongo.Client

func typeinterface2mongo() {
    
    
    var datum2 datum2_instance
    var interfacevalue []interface{}
    
    test_string := `[[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"\"x","[y","'z",[[1,2,3],[1,2,3]]]]`
    if err := json.Unmarshal([]byte(test_string), &interfacevalue); err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println(test_string)
    fmt.Println(interfacevalue)
    datum2_instance.Datum=interfacevalue
    userCollection.InsertOne(context.TODO(), datum2_instance)
    fmt.Println(datum2_instance)
    fmt.Println(datum2_instance.Datum)  
}