Go链接mongodb数据库

参考链接:

https://docs.mongodb.com/drivers/go/

https://www.mongodb.com/blog/search/golang%20quickstart

以下为部分代码:

package main

import (
        "context"
        "fmt"
        "time"

        "go.mongodb.org/mongo-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo/options"
        "go.mongodb.org/mongo-driver/mongo/readpref"
        "go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options"
)

func main() {
        // uri:= "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
        uri := "mongodb+srv://localhost:27017/monitor"
        ctx, cancle := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancle()

        client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))

        if err != nil {
                panic(err)
        }

        defer func() {
                if err = client.Disconnect(ctx); err != nil {
                        panic(err)
                }
        }()

        if err := client.Ping(ctx, readpref.Primary()); err != nil {
                panic(err)
        }
        fmt.Println("Successfully connected and pinged.")
}