From 149f0e7af94113a1b4e9a3514c492d629864ae95 Mon Sep 17 00:00:00 2001 From: Carlos Nieto <jose.carlos@menteslibres.net> Date: Tue, 5 Nov 2013 17:38:09 -0600 Subject: [PATCH] Moving mongo example --- mongo/_example/main.go | 79 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 mongo/_example/main.go diff --git a/mongo/_example/main.go b/mongo/_example/main.go new file mode 100644 index 00000000..0e4993dc --- /dev/null +++ b/mongo/_example/main.go @@ -0,0 +1,79 @@ +package main + +import ( + "fmt" + "time" + "upper.io/db" + _ "upper.io/db/mongo" +) + +var settings = db.Settings{ + Database: `upperio_tests`, + Host: `127.0.0.1`, +} + +type Birthday struct { + Name string `bson:"name"` + Born time.Time `bson:"born"` +} + +func main() { + + sess, err := db.Open("mongo", settings) + + if err != nil { + fmt.Println("Unable to connect:", err.Error()) + return + } + + defer sess.Close() + + birthdayCollection, err := sess.Collection("birthdays") + + if err != nil { + if err != db.ErrCollectionDoesNotExists { + fmt.Println("Could not use collection:", err.Error()) + return + } + } else { + err = birthdayCollection.Truncate() + + if err != nil { + fmt.Println(err.Error()) + return + } + } + + birthdayCollection.Append(Birthday{ + Name: "Hayao Miyazaki", + Born: time.Date(1941, time.January, 5, 0, 0, 0, 0, time.UTC), + }) + + birthdayCollection.Append(Birthday{ + Name: "Nobuo Uematsu", + Born: time.Date(1959, time.March, 21, 0, 0, 0, 0, time.UTC), + }) + + birthdayCollection.Append(Birthday{ + Name: "Hironobu Sakaguchi", + Born: time.Date(1962, time.November, 25, 0, 0, 0, 0, time.UTC), + }) + + var res db.Result + + res = birthdayCollection.Find() + + var birthdays []Birthday + + err = res.All(&birthdays) + + if err != nil { + panic(err.Error()) + return + } + + for _, birthday := range birthdays { + fmt.Printf("%s was born in %s.\n", birthday.Name, birthday.Born.Format("January 2, 2006")) + } + +} -- GitLab