-
Notifications
You must be signed in to change notification settings - Fork 29
/
mongodb1.go
37 lines (34 loc) · 999 Bytes
/
mongodb1.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
//++++++++++++++++++++++++++++++++++++++++
// 《Go Web编程实战派从入门到精通》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 仓库地址:https://gitee.com/shirdonl/goWebActualCombat
// 仓库地址:https://github.com/shirdonl/goWebActualCombat
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
func main() {
var (
client *mongo.Client
err error
db *mongo.Database
collection *mongo.Collection
)
//1.建立连接
if client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017").SetConnectTimeout(5*time.Second)); err != nil {
fmt.Print(err)
return
}
//2.选择数据库 my_db
db = client.Database("my_db")
//3.选择表 my_collection
collection = db.Collection("my_collection")
collection = collection
}