官方文档
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
二 go连接到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")
// 连接到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
三 BSON简介
MongoDB中的JSON文档存储在名为BSON(二进制编码的JSON)的二进制表中。与其他将JSON数据存储为简单字符串和数字的数据库不同,BSON编码扩展了JSON表示,使其包含额外的类型,如int、long、date、浮点数和decimal128。这使得应用程序更容易可靠地处理、排序和比较数据。
DRaw
DD
- D:一个BSON文档。这种类型应该在顺序重要的情况下使用,比如MongoDB命令。
- M:一张无序的map。它和D是一样的,只是它不保持顺序。
- A:一个BSON数组。
- E:D里面的一个元素。
要使用BSON,需要先导入下面的包:
go.mongodb.org/mongo-driver/bson
D
bson.D{{
"name",
bson.D{{
"$in",
bson.A{"张三","李四"},
}},
}}
RawLookup()
D
四 添加文档
4.1 创建一个结构体
type Student struct {
Name string
Age int
}
4.2 添加单个文档
方法:
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中查看:
4.3 添加多个文档
方法:
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中查看: