我有来自 API 的 JSON,我想使用 mgo 包将其保存到 MongoDB。我的 JSON 看起来像这样:
{
"something": "value"
"collection": [
{ "obj1": "value" }
// ... (Variable number of objects here)
]
}
为了保存这些数据,我在我的 Go 应用程序中创建了一个新的 type
,如下所示:
type MyData struct {
Something string
Collection []string // This actually contains more than strings but I'll be happy if I can just get strings saved
}
mongoSess, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
defer mongoSess.Close()
c := mongoSess.DB("mydatabase").C("mycollection")
insertErr := c.Insert(&MyData{something, collection})
此代码有效,但问题是它没有在我的集合字段中保存任何内容,该字段应该是一个 JSON 对象数组。什么都没有。我在我的数据库中获取了 key ,它们是正确的类型,但它们没有数据。这是 Mongo 的输出:
{ "_id" : ObjectId("5520c535a236d8a9a215d096"), "something" : "value", "collection" : [ ] }
谁能看出我做错了什么?我显然是 Go 的新手并且在类型方面遇到了麻烦。
解决方案
这里的答案真的对我帮助很大。我没有正确解释事情是我的错,因为答案让我走上了正确的轨道,但没有直接解决问题。这是实际的解决方案。
package main
import (
"encoding/json"
"github.com/bitly/go-simplejson"
"gopkg.in/mgo.v2"
//"gopkg.in/mgo.v2/bson"
// Other packages are used as well
)
type MyData struct {
Something int
Collection []interface{}
}
func main() {
// I'm using SimpleJson for parsing JSON
collection, cerr := jsonFromExternalApi.Get("collection").Array()
if cerr != nil {
logger.Debug.Fatalln(cerr)
}
// Save response to Mongo (leaving out all the connection code)
c := mongoSess.DB("mydb").C("mycollection")
insertErr := c.Insert(&Producer{npn, licenses })
}
问题是 SimpleJSON 从我的 API 调用返回对象数组作为 []interface{}
。我不知道我可以简单地将一个结构的一部分声明为一个接口(interface),所以我没有纠正 Go 的编译器告诉我的错误,而是让它变得比它应该做的更难。
来自松散类型的脚本语言,像这样的东西真的让我很困惑,有时很难看到好处,但希望有一天这能帮助别人。
最佳答案
看起来你有错误的数据结构。
insertErr := c.Insert(&MyData{something, collection})
something => string
and collection => slice
你的代码应该是这样的:
insertErr := c.Insert(&MyData{"something", []string{"obj1", "value"}})
Here是工作代码。
[{Something:something Collection:[obj1 value]} {Something:something Collection:[obj1 value]} {Something:something Collection:[obj1 value]} {Something:something Collection:[obj1 value]}]
关于json - 如何使用 Go 将对象数组插入 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29454410/