美文网首页
使用MongoDB的Go Driver

使用MongoDB的Go Driver

作者: ytxing | 来源:发表于2019-05-07 16:25 被阅读0次

    本文使用的是官方驱动,https://github.com/mongodb/mongo-go-driver
    ,目前是beta版。

    1. 安装
    go get github.com/mongodb/mongo-go-driver
    

    会输出如下提示,属于正常情况,可以不用管

    package github.com/mongodb/mongo-go-driver: no Go files in $GOPATH/src/github.com/mongodb/mongo-go-driver
    

    官方驱动目前仍有问题,需要把github.com/mongodb/mongo-go-driver目录拷贝到go.mongodb.org/mongo-driver才能用。

    1. 连接
    package main
    
    import (
        "context"
        "fmt"
        "log"
        "time"
    
        //"github.com/mongodb/mongo-go-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo/options"
    )
    
    type Trainer struct {
        Name string
        Age  int
        City string
    }
    
    func main() {
        ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
        client, err := mongo.Connect(ctx, &options.ClientOptions{Hosts: []string{"localhost:27017"}})
    
        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!")
    
        collection := client.Database("test").Collection("trainers")
        _ = collection
    
        err = client.Disconnect(context.TODO())
    
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Connection to MongoDB closed.")
    }
    

    参考:
    https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial

    相关文章

      网友评论

          本文标题:使用MongoDB的Go Driver

          本文链接:https://www.haomeiwen.com/subject/zrceoqtx.html