Date: 1/1/2020Category: Go编程Tag: Golang, MongoDB
如何使用 Golang 连接 MongoDB
连接 MongoDB 非常简单,只需连接 MongoDB 生成的 uri。
然后我们可以使用 client.Database() 函数来确保我们连接到正确的数据库。
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
db := client.Database("testdb")
// disconnect the mongo client when main is completed
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
}
