Last active
November 16, 2016 07:07
-
-
Save arxdsilva/3e1d1fc9c71754aa0a0f7f12e36ae0c5 to your computer and use it in GitHub Desktop.
MongoDB lib to CRUD Example
This file contains hidden or 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
// This is a 'lib' that manipulates mongoDB to insert docs with Pokemon's Structure | |
package main | |
import ( | |
"fmt" | |
"gopkg.in/mgo.v2" | |
"gopkg.in/mgo.v2/bson" | |
) | |
func main() { | |
session := InitDB() | |
c := InitSession(session, "nintendo", "pokemons") | |
InsertP(c, "charmander", 10, 100, "fire") | |
ReadDB(c) | |
DeleteDB(c, "charmander") | |
ReadDB(c) | |
CloseDB(session) | |
} | |
type Pokemon struct { | |
Name string | |
CP int | |
HP int | |
Type string | |
} | |
func InitDB() *mgo.Session { | |
session, err := mgo.Dial("localhost") | |
if err != nil { | |
panic(err) | |
} | |
return session | |
} | |
func InitSession(s *mgo.Session, db, collection string) *mgo.Collection { | |
c := s.DB(db).C(collection) | |
return c | |
} | |
func InsertP(c *mgo.Collection, n string, cp int, hp int, tp string) { | |
err := c.Insert( | |
&Pokemon{n, cp, hp, tp}, | |
) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func ReadDB(c *mgo.Collection) { | |
result := []Pokemon{} | |
err := c.Find(bson.M{}).All(&result) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(result) | |
} | |
func DeleteDB(c *mgo.Collection, n string) { | |
_, err := c.RemoveAll(bson.M{}) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func CloseDB(s *mgo.Session) { | |
s.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment