Skip to content

Instantly share code, notes, and snippets.

@anovanmaximuz
Forked from p4tin/Mongo.go
Created August 15, 2016 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anovanmaximuz/2b7b3a7e343c5b32e72e94bdd6175053 to your computer and use it in GitHub Desktop.
Save anovanmaximuz/2b7b3a7e343c5b32e72e94bdd6175053 to your computer and use it in GitHub Desktop.
Golang Mongo CRUD Example
package mongo
import (
"time"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// Profile - is the memory representation of one user profile
type Profile struct {
Name string `json: "username"`
Password string `json: "password"`
Age int `json: "age"`
LastUpdated time.Time
}
// GetProfiles - Returns all the profile in the Profiles Collection
func GetProfiles() []Profile {
session, err := mgo.Dial("localhost:27017")
if err != nil {
log.Println("Could not connect to mongo: ", err.Error())
return nil
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("ProfileService").C("Profiles")
var profiles []Profile
err = c.Find(bson.M{}).All(&profiles)
return profiles
}
// ShowProfile - Returns the profile in the Profiles Collection with name equal to the id parameter (id == name)
func ShowProfile(id string) Profile {
session, err := mgo.Dial("localhost:27017")
if err != nil {
log.Println("Could not connect to mongo: ", err.Error())
return Profile{}
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("ProfileService").C("Profiles")
profile := Profile{}
err = c.Find(bson.M{"name": id}).One(&profile)
return profile
}
// DeleteProfile - Deletes the profile in the Profiles Collection with name equal to the id parameter (id == name)
func DeleteProfile(id string) bool {
session, err := mgo.Dial("localhost:27017")
if err != nil {
log.Println("Could not connect to mongo: ", err.Error())
return false
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("ProfileService").C("Profiles")
err = c.RemoveId(id)
return true
}
// CreateOrUpdateProfile - Creates or Updates (Upsert) the profile in the Profiles Collection with id parameter
func (p *Profile) CreateOrUpdateProfile() bool {
session, err := mgo.Dial("localhost:27017")
if err != nil {
log.Println("Could not connect to mongo: ", err.Error())
return false
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("ProfileService").C("Profiles")
_ , err = c.UpsertId( p.Name, p )
if err != nil {
log.Println("Error creating Profile: ", err.Error())
return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment