/
main.go
executable file
·58 lines (46 loc) · 1.07 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Example code for Chapter 5.6 from "Build Web Application with Golang"
// Purpose: Shows you have to perform basic CRUD operations for a mongodb driver.
package main
import (
"fmt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Person struct {
Name string
Phone string
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
const (
DB_NAME = "test"
DB_COLLECTION = "people"
)
func main() {
session, err := mgo.Dial("localhost")
checkError(err)
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB(DB_NAME).C(DB_COLLECTION)
err = c.DropCollection()
checkError(err)
ale := Person{"Ale", "555-5555"}
cla := Person{"Cla", "555-1234"}
fmt.Println("Inserting")
err = c.Insert(&ale, &cla)
checkError(err)
fmt.Println("Updating")
ale.Phone = "555-0101"
err = c.Update(bson.M{"name": "Ale"}, &ale)
fmt.Println("Querying")
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).One(&result)
checkError(err)
fmt.Println("Phone:", result.Phone)
fmt.Println("Deleting")
err = c.Remove(bson.M{"name": "Ale"})
checkError(err)
}