douyi4912 2015-04-05 05:27
浏览 146
已采纳

如何使用Go将对象数组插入MongoDB

I have JSON from an API that I want to save to MongoDB using the mgo package. My JSON looks like this:

{
  "something": "value"
  "collection": [
    { "obj1": "value" }
    // ... (Variable number of objects here)
  ]
}

To save this data I've created a new type in my Go application that looks like this:

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

This code works but the problem is that it isn't saving anything in my collection field which should be an array of JSON objects. Nothing at all. I get the keys in my database and they are the right type but they have no data. Here's what the Mongo output is:

{ "_id" : ObjectId("5520c535a236d8a9a215d096"), "something" : "value", "collection" : [ ] }

Can anyone spot what it is I'm doing wrong? I'm obviously new to Go and having trouble with types.

Solution

The answers here really helped me a lot. I'm at fault for not properly explaining things as the answers sent me on the right track but didn't solve the issue directly. Here's what the actual solution is.

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

The issue was that SimpleJSON was returning the array of objects from my API call as a []interface{}. I was not aware I could simply declare part of a struct to be an interface so instead of just correcting what Go's compiler was telling me was wrong I was making it way harder than it should have been.

Coming from loosely typed scripting languages, stuff like this really trips me up and sometimes its hard to see the benefit but hopefully this helps someone out one day.

  • 写回答

2条回答 默认 最新

  • douzhangshao6369 2015-04-05 05:56
    关注

    Looks you have the wrong data structure.

    insertErr := c.Insert(&MyData{something, collection})
    

    something => string and collection => slice

    You code should be like this:

    insertErr := c.Insert(&MyData{"something", []string{"obj1", "value"}})
    

    Here is the working code.

    [{Something:something Collection:[obj1 value]} {Something:something Collection:[obj1 value]} {Something:something Collection:[obj1 value]} {Something:something Collection:[obj1 value]}]
    

    For further reference, mgo has great documentation and you can find sample code and details about running mongodb queries here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名