-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
124 lines (102 loc) · 2.35 KB
/
database.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package routeinjector
import (
"fmt"
"time"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
//@TODO configure db connection
//StartDatabase connects to the Mongo Database
func (m *RouteInjector) StartDatabase() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
m.Session = session
m.Db = session.DB("test")
}
//StopDatabase closes connections with Mongo Database
func (m *RouteInjector) StopDatabase() {
m.Session.Close()
}
//Person is an example schema
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Phone string
Timestamp time.Time
}
// The DB should be droped at startup
var (
IsDrop = true
)
//TestMongo is an initial example of MGO usage
func TestMongo() {
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{"_id": 0, "phone": 1}).One(&result)
if err != nil {
panic(err)
}
fmt.Printf("Phone %+v\n", result.Phone)
result2 := bson.M{}
err = c.Find(bson.M{"name": "Ale"}).Select(bson.M{"_id": 0, "phone": 1}).One(&result2)
if err != nil {
panic(err)
}
fmt.Printf("Phone %+v\n", result2)
// 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)
}