官方文档
https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo
下载地址
https://www.mongodb.com/try/download/community
打开客户端
mongo.exe
创建数据库
use golang_db;
创建集合
db.createCollection("student");
下载驱动
go get go.mongodb.org/mongo-driver/mongo
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")
// 连接到MongoDB
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()
}
运行结果:
[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
[Done] exited with code=0 in 2.819 seconds
MongoDB中的JSON文档存储在名为BSON(二进制编码的JSON)的二进制表中。与其他将JSON数据存储为简单字符串和数字的数据库不同,BSON编码扩展了JSON表示,使其包含额外的类型,如int、long、date、浮点数和decimal128。这使得应用程序更容易可靠地处理、排序和比较数据。
连接MongoDB地Go驱动程序中有两大类型表示BSON数据:D
和Raw
。
类型D
家族被用来简洁地构建使用本地Go类型地BSON对象。这对于构造传递给MongoDB地命令特别有用。D
家族包括四大类:
要使用BSON,需要先导入下面的包:
go.mongodb.org/mongo-driver/bson
下面是一个使用D
类型构建地过滤器文档的例子,它可以用来查找name字段与‘张三’或‘李四’匹配的文档:
bson.D{{
"name",
bson.D{{
"$in",
bson.A{"张三","李四"},
}},
}}
Raw
类型家族用于验证字节切片。还可以使用Lookup()
从原始类型检索单个元素。如果不想将BSON反序列化成另一种类型的开销,那么这是非常有用的。
本文只使用
D
类型。
type Student struct {
Name string
Age int
}
方法:
func (coll *Collection) InsertOne(ctx context.Context, document interface{},
opts ...*options.InsertOneOptions) (*InsertOneResult, error)
实例演示:
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")
// 连接到MongoDB
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
}
type Student struct {
Name string
Age int
}
func insertOne(s Student) {
initDB()
collection := client.Database("golang_db").Collection("student")
insertResult, err := collection.InsertOne(context.TODO(), s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("添加了一条文档记录: %v\n", insertResult.InsertedID)
}
func main() {
s := Student{Name: "Psych", Age: 18}
insertOne(s)
}
运行结果:
[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
添加了一条文档记录: ObjectID("62ee3202c3c3f019d63c34ff")
[Done] exited with code=0 in 3.518 seconds
MongoDB中查看:
方法:
func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},
opts ...*options.InsertManyOptions) (*InsertManyResult, error)
实例演示:
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")
// 连接到MongoDB
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
}
type Student struct {
Name string
Age int
}
func insertMore(students []interface{}) {
initDB()
collection := client.Database("golang_db").Collection("student")
insertManyResult, err := collection.InsertMany(context.TODO(), students)
if err != nil {
log.Fatal(err)
}
fmt.Printf("添加了多条文档记录: %v\n", insertManyResult.InsertedIDs)
}
func main() {
s1 := Student{Name: "Klee", Age: 8}
s2 := Student{Name: "Morax", Age: 1000}
s3 := Student{Name: "Baal", Age: 500}
student := []interface{}{s1, s2, s3}
insertMore(student)
}
运行结果:
[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
添加了多条文档记录: [ObjectID("62ee337502174a1366f86db2") ObjectID("62ee337502174a1366f86db3") ObjectID("62ee337502174a1366f86db4")]
[Done] exited with code=0 in 2.558 seconds
MongoDB中查看:
方法:
func (coll *Collection) Find(ctx context.Context, filter interface{},
opts ...*options.FindOptions) (cur *Cursor, err error)
实例演示:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"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")
// 连接到MongoDB
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 findData() {
initDB()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
collection := client.Database("golang_db").Collection("student")
// c, err := collection.Find(ctx, bson.D{{Key: "name", Value: "Psych"}})
// 单个数据查询
// c, err := collection.Find(ctx, bson.D{{Key: "name", Value: "Morax"}})
c, err := collection.Find(ctx, bson.D{})
if err != nil {
log.Fatal(err)
}
defer c.Close(ctx)
for c.Next(ctx) {
var result bson.D
err := c.Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("查找结果为: %v\n", result)
fmt.Printf("result.Map(): %v\n", result.Map()["name"])
}
if err := c.Err(); err != nil {
log.Fatal(err)
}
}
func main() {
findData()
}
注释内容为单个数据查询,可自行测试
运行结果:
[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
查找结果为: [{_id ObjectID("62ee3202c3c3f019d63c34ff")} {name Psych} {age 18}]
result.Map(): Psych
查找结果为: [{_id ObjectID("62ee337502174a1366f86db2")} {name Klee} {age 8}]
result.Map(): Klee
查找结果为: [{_id ObjectID("62ee337502174a1366f86db3")} {name Morax} {age 1000}]
result.Map(): Morax
查找结果为: [{_id ObjectID("62ee337502174a1366f86db4")} {name Baal} {age 500}]
result.Map(): Baal
[Done] exited with code=0 in 2.482 seconds
方法:
func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{},
opts ...*options.UpdateOptions) (*UpdateResult, error)
func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{},
opts ...*options.UpdateOptions) (*UpdateResult, error)
实例演示:
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"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")
// 连接到MongoDB
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 updateData() {
initDB()
ctx := context.TODO()
defer client.Disconnect(ctx)
c := client.Database("golang_db").Collection("student")
update := bson.D{{"$set", bson.D{{Key: "name", Value: "钟离"}, {Key: "age", Value: 1200}}}}
// 更新条件 name Morax
// 更新为 name 钟离 age 1200
ur, err := c.UpdateMany(ctx, bson.D{{Key: "name", Value: "Morax"}}, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("修改文档数量: %v\n", ur.ModifiedCount)
}
func main() {
updateData()
}
运行结果:
[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
修改文档数量: 1
[Done] exited with code=0 in 2.529 seconds
MongoDB中查看:
方法:
func (coll *Collection) DeleteMany(ctx context.Context, filter interface{},
opts ...*options.DeleteOptions) (*DeleteResult, error)
func (coll *Collection) DeleteOne(ctx context.Context, filter interface{},
opts ...*options.DeleteOptions) (*DeleteResult, error)
实例演示:
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"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")
// 连接到MongoDB
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 deleteData() {
initDB()
ctx := context.TODO()
defer client.Disconnect(ctx)
c := client.Database("golang_db").Collection("student")
dr, err := c.DeleteMany(ctx, bson.D{{Key: "name", Value: "Psych"}})
if err != nil {
log.Fatal(err)
}
fmt.Printf("删除文档数量: %v\n", dr.DeletedCount)
}
func main() {
deleteData()
}
运行结果:
[Running] go run "e:\golang开发学习\go_pro\test.go"
MongoDB 连接成功
删除文档数量: 1
[Done] exited with code=0 in 3.698 seconds
MongoDB中查看: