Created
September 25, 2015 07:30
-
-
Save IndianGuru/74234a2e023a36238142 to your computer and use it in GitHub Desktop.
mongohqconnect.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:dbpassword@ds051523.mongolab.com: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", "klaste@posteo.de"}, | |
&Person{"Nishant Modak", "modak.nishant@gmail.com"}, | |
&Person{"Prathamesh Sonpatki", "csonpatki@gmail.com"}, | |
&Person{"murtuza kutub", "murtuzafirst@gmail.com"}, | |
&Person{"aniket joshi", "joshianiket22@gmail.com"}, | |
&Person{"Michael de Silva", "michael@mwdesilva.com"}, | |
&Person{"Alejandro Cespedes Vicente", "cesal_vizar@hotmail.com"}) | |
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