使用MongoDB的Go Driver
2019-05-07 本文已影响0人
ytxing
本文使用的是官方驱动,https://github.com/mongodb/mongo-go-driver
,目前是beta版。
- 安装
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
才能用。
- 连接
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