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

时间:2015-12-24 06:07:05

标签: mongodb go mgo

我的json如下所示,

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

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

3 个答案:

答案 0 :(得分:6)

Unmarshal JSON到[] interface {}和insert结果在数据库中。假设var start = "A".charCodeAt(0); var end = "H".charCodeAt(0); for (var i = start; i <= end; i += 1) { var row = String.fromCharCode(i); document.getElementById('cost' + row).innerHTML = currentCost[i - start]; document.getElementById('amount' + row).innerHTML = building[i - start]; document.getElementById('bonus' + row).innerHTML = currentBonuses[i - start]; } mgo.Collectionc是包含JSON值的[]字节,请使用以下代码:

data

答案 1 :(得分:1)

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

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

作为json进入mongodb:

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


答案 2 :(得分:0)

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

如果首先拥有Xml数据,则需要使用此软件包(“ github.com/basgys/goxml2json”)转换为json格式

UIButton