title: How to insert array of objects into MongoDB using Go
body: <p>I have JSON from an API that I want to save to MongoDB using the mgo package. My JSON looks like this:</p>
  
  <pre><code>{
    "something": "value"
    "collection": [
      { "obj1": "value" }
      // ... (Variable number of objects here)
    ]
  }
  </code></pre>
  
  <p>To save this data I've created a new <code>type</code> in my Go application that looks like this:</p>
  
  <pre><code>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(&amp;MyData{something, collection})
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>{ "_id" : ObjectId("5520c535a236d8a9a215d096"), "something" : "value", "collection" : [ ] }
  </code></pre>
  
  <p>Can anyone spot what it is I'm doing wrong? I'm obviously new to Go and having trouble with types.</p>
  
  <h3>Solution</h3>
  
  <p>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.</p>
  
  <pre><code>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(&amp;Producer{npn, licenses })
  }
  </code></pre>
  
  <p>The issue was that SimpleJSON was returning the array of objects from my API call as a <code>[]interface{}</code>. 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.</p>
  
  <p>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.</p>