How to insert a json object array to mongodb in golang

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

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,但没有找到关于上述用例的足够示例。希望你能提供一些解决方案。

英文:

My json looks like the following,

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

This json comes in string format and I want the objects in the json array to be inserted as individual records in mongodb. I referred to https://labix.org/mgo but wasn't able to find enough examples on the above use-case. Appreciate your thoughts in finding a solution.

答案1

得分: 11

将JSON解组为[]interface{},并将结果插入数据库。假设c是一个mgo.Collectiondata是一个包含JSON值的[]byte,请使用以下代码:

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

这段代码将JSON数据解析为一个[]interface{}切片,并将其插入到数据库中。如果解析或插入过程中出现错误,可以在相应的错误处理部分进行处理。

英文:

Unmarshal the JSON to []interface{} and insert the result in the database. Assuming that c is an mgo.Collection and data is a []byte containing the JSON value, use the following code:

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

答案2

得分: 2

在这个例子中,我将把混合数组存储在 MongoDB 中作为 JSON 数据:

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") // 从 db() 中获取集合 "users",db() 返回 *mongo.Client

func typeinterface2mongo() {
	var datum2_instance datum2
	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)
}

请注意,这只是代码的一部分,其他部分可能会影响代码的运行。

英文:

In this example I will store the mixed array

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

inside the mongodb as the 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)	
}


答案3

得分: 1

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

如果您有XML数据,首先需要使用这个包("github.com/basgys/goxml2json")将其转换为JSON格式。

type JsonFileResponse struct {
	JsonData string `bson:"JsonData" json:"JsonData"`
}

// 步骤1:
jsonData, err := xml2json.Convert(xml)
if err != nil {
    panic("在将XML转换为JSON时出错", err)
}

// 步骤2:使用您的MongoDB凭据打开会话
collection := session.DB("数据库名称").C("集合名称")
err = collection.Insert(JsonFileResponse{JsonData: json.String()})
if err != nil {
    log.Fatal(err)
}

请注意,这只是代码的翻译部分,不包括任何其他内容。

英文:

If you have json data already please follow from step 2.

If you have Xml data first you need to convert to the json format by using this package("github.com/basgys/goxml2json")

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

huangapple
  • 本文由 发表于 2015年12月24日 14:07:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/34448102.html
匿名

发表评论

匿名网友

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

确定