-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmongo.go
90 lines (79 loc) · 1.68 KB
/
mongo.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
package food
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"strings"
"time"
)
var Session *mgo.Session
var FoodsCollection *mgo.Collection
var WordsCollection *mgo.Collection
var MetaCollection *mgo.Collection
var TaskCollection *mgo.Collection
var DetailCollection *mgo.Collection
type SJson map[string]interface{}
func (j *SJson) Get(key string) *interface{} {
path := strings.Split(key, ".")
last := j
for index, k := range path {
if index != len(path)-1 {
v := (*last)[k].(SJson)
last = &v
} else {
v := (*last)[k]
return &v
}
}
return nil
}
func saveMetaInterval() {
for {
time.Sleep(time.Second * 5)
saveMeta()
}
}
var Meta = SJson{
"cats": []int{1, 2, 3, 4},
"cats_progress": SJson{
"1": 23,
"2": 46,
"3": SJson{},
},
}
func saveMeta() {
if MetaCollection != nil {
log.Println("保存元信息", Meta)
_, err := MetaCollection.Upsert(bson.M{"_id": "meta"}, Meta)
if err != nil {
log.Println(err)
}
} else {
log.Println("保存meta失败")
}
}
func loadMeta() {
result := SJson{}
err := MetaCollection.Find(bson.M{"_id": "meta"}).One(&result)
if err != nil {
log.Println(err)
return
}
log.Println("读取meta", result)
Meta = result
}
func conMongo() {
url := "mongodb://root:[email protected]:27017/admin"
s, err := mgo.Dial(url)
if err != nil {
panic(err)
}
s.Refresh()
Session = s
Session.SetMode(mgo.Monotonic, true)
FoodsCollection = Session.DB("playground").C("foods")
WordsCollection = Session.DB("playground").C("foods_words")
MetaCollection = Session.DB("playground").C("foods_meta")
TaskCollection = Session.DB("playground").C("foods_task")
DetailCollection = Session.DB("playground").C("foods_detail")
}