Skip to content

Instantly share code, notes, and snippets.

@IndianGuru
Created September 25, 2015 07:30
Show Gist options
  • Save IndianGuru/74234a2e023a36238142 to your computer and use it in GitHub Desktop.
Save IndianGuru/74234a2e023a36238142 to your computer and use it in GitHub Desktop.
mongohqconnect.go
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"os"
)
type Person struct {
Name string
Email string
}
func main() {
// Do the following:
// In a command window:
// set MONGOLAB_URL=mongodb://IndianGuru:[email protected]:51523/godata
// IndianGuru is my username, replace the same with yours. Type in your password.
uri := os.Getenv("MONGOLAB_URL")
if uri == "" {
fmt.Println("no connection string provided")
os.Exit(1)
}
sess, err := mgo.Dial(uri)
if err != nil {
fmt.Printf("Can't connect to mongo, go error %v\n", err)
os.Exit(1)
}
defer sess.Close()
sess.SetSafe(&mgo.Safe{})
collection := sess.DB("godata").C("user")
err = collection.Insert(&Person{"Stefan Klaste", "[email protected]"},
&Person{"Nishant Modak", "[email protected]"},
&Person{"Prathamesh Sonpatki", "[email protected]"},
&Person{"murtuza kutub", "[email protected]"},
&Person{"aniket joshi", "[email protected]"},
&Person{"Michael de Silva", "[email protected]"},
&Person{"Alejandro Cespedes Vicente", "[email protected]"})
if err != nil {
log.Fatal("Problem inserting data: ", err)
return
}
result := Person{}
err = collection.Find(bson.M{"name": "Prathamesh Sonpatki"}).One(&result)
if err != nil {
log.Fatal("Error finding record: ", err)
return
}
fmt.Println("Email Id:", result.Email)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment