forked from pibigstar/go-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb_test.go
91 lines (83 loc) · 1.73 KB
/
mongodb_test.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
package test
import (
"context"
"go-demo/utils/env"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"testing"
"time"
)
type User struct {
Name string `bson:"name"`
Password string `bson:"password"`
Age int `bson:"age"`
}
func TestMongoDB(t *testing.T) {
if env.IsCI() {
return
}
var (
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
)
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://ip:27017"))
if err != nil {
t.Error(err)
}
// 获取collection对象,如果没有则会自动创建
collection := client.Database("test").Collection("user")
// 插入
user := &User{
Name: "pibigstar",
Password: "123456",
Age: 20,
}
resp, err := collection.InsertOne(ctx, user)
if err != nil {
t.Error(err)
}
t.Log(resp.InsertedID.(primitive.ObjectID).Hex())
users := []interface{}{
&User{
Name: "小明",
Password: "666",
Age: 20,
},
&User{
Name: "小花",
Password: "555",
Age: 18,
},
}
// 批量插入
if manyResult, err := collection.InsertMany(ctx, users); err == nil {
for _, id := range manyResult.InsertedIDs {
t.Log(id.(primitive.ObjectID).Hex())
}
}
// 查询
var skip int64 = 0
var limit int64 = 10
opts := &options.FindOptions{
Skip: &skip,
Limit: &limit,
}
cur, err := collection.Find(ctx, bson.D{}, opts)
if err != nil {
t.Error(err)
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var result User
err := cur.Decode(&result)
if err != nil {
t.Error(err)
}
// do something with result....
t.Logf("%+v", result)
}
if err := cur.Err(); err != nil {
t.Error(err)
}
}