-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb.go
120 lines (100 loc) · 1.83 KB
/
mongodb.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
package mongodb
import (
"context"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
dbName = "study_mongodb"
cInventory = "inventory"
cCharacters = "characters"
cStores = "stores"
)
var (
client *mongo.Client
db *mongo.Database
inventory *mongo.Collection
characters *mongo.Collection
stores *mongo.Collection
)
func Init(url string) error {
opt := options.Client().ApplyURI(url)
c, err := mongo.Connect(context.TODO(), opt)
if err != nil {
return err
}
err = c.Ping(context.TODO(), nil)
if err != nil {
return err
}
client = c
db = client.Database(dbName)
inventory = db.Collection(cInventory)
characters = db.Collection(cCharacters)
stores = db.Collection(cStores)
return nil
}
// 为了使数据清晰, 所以定义了多种文档类型
type Size struct {
H float32
W float32
UOM string
}
type Doc1 struct {
Item string
QTY int
Tags []string
Size Size
}
type Doc2 struct {
Item string
QTY int
Size Size
Status string
}
type Instock struct {
Warehouse string
QTY int
}
type Doc3 struct {
Item string
Status string
Size Size
Instock []Instock
}
type Doc4 struct {
Item string
Instock []Instock
}
type Doc5 struct {
Item string
QTY int
Tags []string
DimCm []float32
}
// Doc6 Doc7 用于测试空值
type Doc6 struct {
ID primitive.ObjectID `bson:"_id"`
Item *int
}
type Doc7 struct {
ID primitive.ObjectID `bson:"_id"`
}
type Doc8 struct {
ID primitive.ObjectID `bson:"_id"`
Char string
Class string
LVL int
}
type Doc9 struct {
ID primitive.ObjectID `bson:"_id"`
Name string
Description string
}
type Doc10 struct {
ID primitive.ObjectID `bson:"_id"`
Name string
Description string
Score float32
}