Skip to content

Instantly share code, notes, and snippets.

@polds
Created November 11, 2013 10:25
Show Gist options
  • Save polds/7411034 to your computer and use it in GitHub Desktop.
Save polds/7411034 to your computer and use it in GitHub Desktop.
Mgo Example
package main
import (
"fmt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"time"
)
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Phone string
Timestamp time.Time
}
var (
IsDrop = true
)
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
// Drop Database
if IsDrop {
err = session.DB("test").DropDatabase()
if err != nil {
panic(err)
}
}
// Collection People
c := session.DB("test").C("people")
// Index
index := mgo.Index{
Key: []string{"name", "phone"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = c.EnsureIndex(index)
if err != nil {
panic(err)
}
// Insert Datas
err = c.Insert(&Person{Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()},
&Person{Name: "Cla", Phone: "+66 33 1234 5678", Timestamp: time.Now()})
if err != nil {
panic(err)
}
// Query One
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).Select(bson.M{"phone": 0}).One(&result)
if err != nil {
panic(err)
}
fmt.Println("Phone", result)
// Query All
var results []Person
err = c.Find(bson.M{"name": "Ale"}).Sort("-timestamp").All(&results)
if err != nil {
panic(err)
}
fmt.Println("Results All: ", results)
// Update
colQuerier := bson.M{"name": "Ale"}
change := bson.M{"$set": bson.M{"phone": "+86 99 8888 7777", "timestamp": time.Now()}}
err = c.Update(colQuerier, change)
if err != nil {
panic(err)
}
// Query All
err = c.Find(bson.M{"name": "Ale"}).Sort("-timestamp").All(&results)
if err != nil {
panic(err)
}
fmt.Println("Results All: ", results)
}
package main
import (
"fmt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Person struct {
Name string
Phone string
}
func main() {
session, err := mgo.Dial("server1.example.com,server2.example.com")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("people")
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
&Person{"Cla", "+55 53 8402 8510"})
if err != nil {
panic(err)
}
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).One(&result)
if err != nil {
panic(err)
}
fmt.Println("Phone:", result.Phone)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment