Package mongo provides a MongoDB Driver API for Go.
Basic usage of the driver starts with creating a Client from a connection string. To do so, call Connect:
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://foo:bar@localhost:27017"))
if err != nil { return err }
This will create a new client and start monitoring the MongoDB server on localhost. The Database and Collection types can be used to access the database:
collection := client.Database("baz").Collection("qux")
A Collection can be used to query the database or insert documents:
res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID
驱动包获取
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
go get go.mongodb.org/mongo-driver/mongo
首先介绍下 Context
这个时候就轮到Context登场了。Context顾名思义是协程的上下文,主要用于跟踪协程的状态,可以做一些简单的协程控制,也能记录一些协程信息。
连接 mongodb 数据库
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var client *mongo.Client
func initDB() {
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
var err error
c, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = c.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("MongoDB 连接成功")
client = c
}
func main() {
initDB()
}
官方案例
This will create a new client and start monitoring the MongoDB server on localhost. The Database and Collection types can be used to access the database:
collection := client.Database("gobase").Collection("student")
A Collection can be used to query the database or insert documents:
res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil {
log.Fatal(err)
}
id := res.InsertedID
fmt.Print(id)
结构体插入数据库
首先, 创建一些Trainer结构体用来插入到数据库:
ash := Trainer{"Ash", 10, "Pallet Town"}
misty := Trainer{"Misty", 10, "Cerulean City"}
brock := Trainer{"Brock", 15, "Pewter City"}
插入一个单独的文档, 使用 collection.InsertOne()函数:
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
同时插入多个文档, collection.InsertMany() 函数会采用一个slice对象:
trainers := []interface{}{misty, brock}
insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
查询一个文档, 你需要一个filter文档, 以及一个指针在它里边保存结果的解码。要查询单个的文档, 使用collection.FindOne()函数。这个函数返回单个的结果,被解码成为一个值。
可以使用和上面使用过的update查询一样的filter变量来匹配一个name是Ash的文档。
create a value into which the result can be decoded
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)