title: Dynamically insert multiple documents using mgo golang mongodb
body: <p>How can I insert an array of documents into MongoDB with <a href="https://godoc.org/labix.org/v2/mgo" rel="nofollow noreferrer">mgo</a> library using only a <strong>single</strong> DB call as in <a href="https://docs.mongodb.com/manual/reference/method/db.collection.insert/#insert-multiple-documents" rel="nofollow noreferrer">db.collection.insert()</a>?</p>
  
  <p>I have the following <code>Transaction</code> structure:</p>
  
  <pre><code>    type Transaction struct {
      Brand         string `json:"brand"`
      Name          string `json:"name"`
      Plu           string `json:"plu"`
      Price         string `json:"price"`
    }
  </code></pre>
  
  <p>From a <code>POST</code> request I will recieve an array of these structures. I want to insert them into MongoDB as <em>individual</em> documents but using a single DB call as explained in <a href="https://docs.mongodb.com/manual/reference/method/db.collection.insert/#insert-multiple-documents" rel="nofollow noreferrer">db.collection.insert()</a> </p>
  
  <p>I tried using <a href="https://godoc.org/labix.org/v2/mgo#Collection.Insert" rel="nofollow noreferrer"><code>c.Insert</code></a> of mgo </p>
  
  <p>The following is the code snippet:</p>
  
  <pre><code>  func insertTransaction(c *gin.Context) {
      var transactions []Transaction
      err := c.BindJSON(&amp;transactions)
      if err != nil {
          c.AbortWithStatusJSON(http.StatusBadRequest, map[string]string{"error":"invalid JSON"})
          return
      }
      err = InsertTransactons(transactions)
      if err != nil {
          c.AbortWithStatusJSON(http.StatusInternalServerError, &amp;map[string](interface{}){
              "status":  "error",
              "code":    "500",
              "message": "Internal server error",
              "error": err,
          })
          return
      }
      c.JSON(http.StatusCreated, &amp;map[string](interface{}){
          "status":  "success",
          "code":    "0",
          "message": "created",
      })
    }
  
  
    func InsertTransactons(u []Transaction) error {
      s := GetSession()
      defer s.Close()
      c := s.DB(DB).C(TransactionColl)
      err := c.Insert(u...)
      if err != nil {
          return err
      }
      return nil
    }
  </code></pre>
  
  <p>But as I compile and run the code, I get the following error:</p>
  
  <blockquote>
    <p>go/database.go:34:17: cannot use u (type *[]Transaction) as type
    []interface {} in argument to c.Insert</p>
  </blockquote>