MongoDB学习笔记
简介
MongoDB 是一个基于文档的通用分布式部署的现代应用数据库。数据存储格式跟 JSON 格式类似,每个数据可以看成是一个对象并可以嵌套。
安装请参考MongoDB Install 或使用 docker 安装。
docker run --name some-mongo -p 27017:27017 -d mongo:tag
–name 表示指定这个容器的名字;-p 容器端口到本地端口映射;-d 后端运行;tag
指定 MongoDB 的版本。
更多关于 docker 安装 MongoDB 的细节说明。
Go语言使用示例
在 Go Module 模式下安装:go get go.mongodb.org/mongo-driver/mongo
,其他包管理模式请自行 baidu
或 google
。
导入数据库驱动和创建客户端
import(
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
连接数据库
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
断开数据库连接
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
使用 Ping
方法测试是否已经连接到了数据库
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = client.Ping(ctx, readpref.Primary())
插入数据
import(
"go.mongodb.org/mongo-driver/bson"
)
// 指定数据库,创建操作对象
collection := client.Database("testing").Collection("numbers")
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
id := res.InsertedID
查询数据
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cur, err := collection.Find(ctx, bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(ctx)
for cur.Next(ctx) {
var result bson.M
err := cur.Decode(&result)
if err != nil { log.Fatal(err) }
// do something with result....
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
查询一条数据
var result struct {
Value float64
}
filter := bson.M{"name": "pi"}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = collection.FindOne(ctx, filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
// Do something with result...
示例完整代码
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func init() {
log.SetFlags(log.Lshortfile)
}
func main() {
// create timeout context based on background root context
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// create client
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
handError(err, "Create client failed")
defer func() {
if err = client.Disconnect(ctx); err != nil {
handError(err, "Disconnect failed")
}
}()
// connect mongodb
err = client.Connect(ctx)
handError(err, "Connect server failed")
// ping
err = client.Ping(ctx, readpref.Primary())
handError(err, "Ping client failed")
// insert one record
collection := client.Database("testing").Collection("numbers")
_, err = collection.InsertOne(ctx, bson.M{
"name": "ty",
"age": 123,
})
handError(err, "Insert record failed")
// select all record
cur, err := collection.Find(ctx, bson.D{})
handError(err, "Find all record failed")
defer cur.Close(ctx)
for cur.Next(ctx) {
var result bson.M
err = cur.Decode(&result)
handError(err, "Loop result error")
fmt.Println(result)
}
// check error return by cursor
err = cur.Err()
handError(err, "Last cursor failed")
// select one record
var result struct {
Name string
Age float64
}
filter := bson.M{"name": "ty"}
err = collection.FindOne(ctx, filter).Decode(&result)
handError(err, "Find one record failed")
fmt.Println(result)
// delete all record
res, err := collection.DeleteMany(ctx, filter)
handError(err, "Delete record failed")
fmt.Println(res)
}
func handError(err error, info string) {
if err != nil {
log.Fatalln(info+": ", err)
}
}