go語言之操作mongodb
阿新 • • 發佈:2021-08-24
go語言操作mongodb
程式碼
// mongodb CRUD // ctx bson.D ? package main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type Student struct { Name string City string Score float32 } func CheckError(err error, line int){ if err != nil { fmt.Println("error line:", line) log.Fatal(err) } } func query(ctx context.Context, collection *mongo.Collection) { // https://blog.csdn.net/ootw/article/details/115902576, 需要規範化的編寫才不會飄黃 sort := bson.D{{Key:"score", Value:1}} // 排序, 1升序, -1降序 filter := bson.D{{Key:"score", Value:bson.D{{Key:"$gt", Value:3}}}} // 過濾條件 score > 3 findOption := options.Find() findOption.SetSort(sort) findOption.SetLimit(10) // 最多返回10個 findOption.SetSkip(0) // 跳過前三個 cursor, err := collection.Find(ctx, filter, findOption) if err != nil { log.Fatal(err) } // 關閉迭代器 defer cursor.Close(ctx) for cursor.Next(ctx) { var doc Student err := cursor.Decode(&doc) if err != nil { log.Fatal(err) } fmt.Printf("%s %s %.2f\n", doc.Name, doc.City, doc.Score) } } func create(ctx context.Context, collection *mongo.Collection) { // 插入一個文件 doc := Student{ Name: "啊哈", City: "香港", Score: 86, } ret, _ := collection.InsertOne(ctx, doc) // CheckError(err, 64) // 每個doc都會有一個全世界唯一的ID(時間+空間唯一) fmt.Printf("insert id %v\n", ret.InsertedID) // 插入多個doc docs := []interface{}{ Student{ Name: "小C", City: "上海", Score: 90, }, Student{ Name: "小D", City: "杭州", Score: 89, }, } manyRes, err := collection.InsertMany(ctx, docs) fmt.Printf("insert many ids %v\n", manyRes.InsertedIDs) CheckError(err, 85) } func update(ctx context.Context, collection *mongo.Collection) { fileter := bson.D{{Key:"city", Value:"杭州"}} update := bson.D{{Key:"$inc", Value: bson.D{{Key: "score", Value: 89}}}} res, err := collection.UpdateMany(ctx, fileter, update) CheckError(err, 96) fmt.Printf("update %d doc \n", res.ModifiedCount) } func delete(ctx context.Context, collection *mongo.Collection) { filter := bson.D{{Key:"name", Value: "小D"}} res, err := collection.DeleteMany(ctx, filter) CheckError(err, 105) fmt.Printf("delete %d doc \n", res.DeletedCount) } func main() { // 不懂 ctx := context.Background() // 設定客戶端連線配置 clientOptions := options.Client().ApplyURI("mongodb://172.30.1.128:27017") clientOptions.SetConnectTimeout(time.Second) clientOptions.SetAuth(options.Credential{Username: "admin", Password: "Tck151##a", AuthSource: "admin"}) // 連線到mongodb client, err := mongo.Connect(ctx, clientOptions) if err != nil { log.Fatal(err) } err = client.Ping(ctx, nil) if err != nil { log.Fatal(err) } // 釋放連線 defer client.Disconnect(ctx) collection := client.Database("test").Collection("student") query(ctx, collection) // create(ctx, collection) // update(ctx, collection) // delete(ctx, collection) } ``
本文來自部落格園,作者:zhanghuiyan,轉載請註明原文連結:https://www.cnblogs.com/zhanghuiyan/p/15179684.html