Skip to content

Instantly share code, notes, and snippets.

@moongears
Last active December 1, 2021 00:38
Show Gist options
  • Save moongears/99b5a2f6f8087008a2cd to your computer and use it in GitHub Desktop.
Save moongears/99b5a2f6f8087008a2cd to your computer and use it in GitHub Desktop.
Golang Mongo insert
package main
import (
"fmt"
"time"
"os"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string `bson:"nm"`
Phone string `bson:"ph"`
Created time.Time `bson:"c,omitempty"`
}
func main() {
//get session
session, err := mgo.Dial("localhost")
if err != nil {
fmt.Printf("dial fail %v\n", err)
os.Exit(1)
}
defer session.Close()
//error check on every access
session.SetSafe(&mgo.Safe{})
//get collection
collection := session.DB("test_db").C("people")
//build record
people := [...]Person{Person{ID: bson.NewObjectId(),
Name: "Gordon Sumner",
Phone: "+11 22 3456 7890",
Created: time.Now()},
Person{ID: bson.NewObjectId(),
Name: "Andy Summers",
Phone: "+11 22 4567 7890",
Created: time.Now()},
Person{ID: bson.NewObjectId(),
Name: "Stewart Copeland",
Phone: "+11 22 5678 7890",
Created: time.Now()}}
//insert
for i, v := range people {
err = collection.Insert(v)
if err != nil {
fmt.Printf("insert fail #%d %v\n", i, err)
os.Exit(1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment