golang 接 mongodb 簡單學習

內容說明

記錄用 golang 串接 mongodb,也會提供必要的註解

資料夾、文件結構圖

1
2
3
4
5
6
7
8
.
├── CRUD
│ └── crud.go
├── go.mod
├── go.sum
└── main.go

1 directory, 4 files

main.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
package main

import (
crud "binarytree/CRUD"
"context"
"fmt"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
// credential := options.Credential{
// Username: "xxxx",
// Password: "bbbb",
// }

//clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential) //有帳號的情況
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017") //沒有帳號密碼下直接連
ctx := context.Background()
client, err := mongo.Connect(ctx, clientOpts)
err = client.Ping(ctx, nil) //若沒有成功連線,則會返回error
if err != nil {
fmt.Println(err) //Connect似乎不吐error
return
}

//create schema
_, collection := crud.CreateDatabase(client, "test", "member")

//create data
person := crud.Person{Name: "david", Age: 23, Email: "gmail.com"}
person.ID = crud.InsertDocument(collection, person)
fmt.Println(person.ID)

//find data
otherOne := crud.FindDocumentByID(collection, person.ID)
fmt.Println(otherOne.Name, otherOne.Email)

//update data
crud.UpdateDocument(collection, person.ID, 50)

}

// golang 連 mongodb
//https://datapool.tw/2023/08/22/golang-mongodb-connection-%E5%8A%A0-ping-%E7%A2%BA%E8%AA%8D%E9%80%A3%E7%B7%9A/
//

crud.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
package crud

import (
"context"
"fmt"
"log"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)

func CreateDatabase(client *mongo.Client, dbName string, collectionName string) (*mongo.Database, *mongo.Collection) {
database := client.Database(dbName)
//collection = sql 的 schema
collection := database.Collection(collectionName)
return database, collection
}

type Person struct {
ID primitive.ObjectID `bson:"_id,omitempty"` //mongodb 的 unique id 格式
Name string `bson:"name"`
Age int `bson:"age"`
Email string `bson:"email"`
}

func InsertDocument(collection *mongo.Collection, person Person) primitive.ObjectID {
insertResult, err := collection.InsertOne(context.Background(), person)
if err != nil {
log.Fatal(err)
}

fmt.Println("Inserted document with ID:", insertResult.InsertedID)
return insertResult.InsertedID.(primitive.ObjectID)
//return fmt.Sprintf("%s", insertResult.InsertedID)
}

func FindDocumentByID(collection *mongo.Collection, id primitive.ObjectID) Person {
var result Person

filter := bson.D{{"_id", id}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}

return result
}

func UpdateDocument(collection *mongo.Collection, id primitive.ObjectID, newAge int) {
filter := bson.D{{"_id", id}}
update := bson.D{
{"$set", bson.D{ // $set 只修改資料內的特定部分
{"age", newAge},
}},
}

updateResult, err := collection.UpdateOne(context.Background(), filter, update)
if err != nil {
log.Fatal(err)
}

fmt.Printf("Matched %v document(s) and modified %v document(s)\n", updateResult.MatchedCount, updateResult.ModifiedCount)
}

func DeleteDocument(collection *mongo.Collection, id primitive.ObjectID) {
filter := bson.D{{"_id", id}}
deleteResult, err := collection.DeleteOne(context.Background(), filter)
if err != nil {
log.Fatal(err)
}

fmt.Printf("Deleted %v document(s)\n", deleteResult.DeletedCount)
}

參考連結

Golang MongoDB connection 加 Ping 確認連線 by DataPool inc.

  • 版權聲明: 本部落格所有文章除有特別聲明外,均採用 Apache License 2.0 許可協議。轉載請註明出處!
  • © 2020-2024 John Doe
  • Powered by Hexo Theme Ayer
  • PV: UV: