TOP

Go MongoDB官方数据库驱动之增删改查
2019-08-14 00:07:11 】 浏览:45
Tags:MongoDB 官方 数据库 驱动 删改

package main

import (
    "context"
    "fmt"
    "log"

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

// Trainer type is used for later
type Trainer struct {
    Name string
    Age  int
    City string
}

func main() {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")

    // Get collection
    collection := client.Database("test").Collection("trainers")

    ash := Trainer{"Ash", 10, "Pallet Town"}
    misty := Trainer{"misty", 10, "Cerulean City"}
    brock := Trainer{"Brock", 15, "Pewter City"}

    // Insert
    insertResult, err := collection.InsertOne(context.TODO(), ash)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Inserted a single document: ", insertResult.InsertedID)

    trainers := []interface{}{misty, brock}

    insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)

    // Update
    filter := bson.D{{"name", "Ash"}}

    update := bson.D{
        {"$inc", bson.D{
            {"age", 1},
        }},
    }

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

    fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

    // Search 
    var result Trainer
    err = collection.FindOne(context.TODO(), filter).Decode(&result)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Found a single document: %+v\n", result)

    findOptions := options.Find()
    findOptions.SetLimit(5)

    var results []*Trainer

    cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
    if err != nil {
        log.Fatal(err)
    }

    for cur.Next(context.TODO()) {
        var elem Trainer
        err := cur.Decode(&elem)
        if err != nil {
            log.Fatal(err)
        }

        results = append(results, &elem)
    }

    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }

    cur.Close(context.TODO())

    fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)

    // Delete 
    deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)
}

One
Two


Go MongoDB官方数据库驱动之增删改查 https://www.cppentry.com/bencandy.php?fid=78&id=228480

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Go 基本数据类型 下一篇基于go语言结合微信小程序开发的..