Go语言学习笔记之golang操作MongoDB数据库
作者:PPPsych 时间:2024-01-27 05:06:23
一 下载安装驱动
官方文档
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。这使得应用程序更容易可靠地处理、排序和比较数据。
连接MongoDB地Go驱动程序中有两大类型表示BSON数据:D
和Raw
。
类型D
家族被用来简洁地构建使用本地Go类型地BSON对象。这对于构造传递给MongoDB地命令特别有用。D
家族包括四大类:
D:一个BSON文档。这种类型应该在顺序重要的情况下使用,比如MongoDB命令。
M:一张无序的map。它和D是一样的,只是它不保持顺序。
A:一个BSON数组。
E:D里面的一个元素。
要使用BSON,需要先导入下面的包:
go.mongodb.org/mongo-driver/bson
下面是一个使用D
类型构建地过滤器文档的例子,它可以用来查找name字段与‘张三’或‘李四’匹配的文档:
bson.D{{
"name",
bson.D{{
"$in",
bson.A{"张三","李四"},
}},
}}
Raw
类型家族用于验证字节切片。还可以使用Lookup()
从原始类型检索单个元素。如果不想将BSON反序列化成另一种类型的开销,那么这是非常有用的。
本文只使用
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中查看:
来源:https://blog.csdn.net/qq_39280718/article/details/126199197


猜你喜欢
Python读写及备份oracle数据库操作示例

Vue子组件监听父组件值的变化
如何用Python破解wifi密码过程详解

获取python的list中含有重复值的index方法
简单总结Python中序列与字典的相同和不同之处
用ASP对网页进行限制性的访问
PHP+Ajax实现无刷新分页实例详解(附demo源码下载)

php中运用http调用的GET和POST方法示例
Python接口传输url与flask数据详解

Python基于pillow库实现生成图片水印
Pytorch可视化的几种实现方法

pycharm自动生成文件注释和函数注释

vantUI 获得piker选中值的自定义ID操作

K8ssandra入门教程之Linux上部署K8ssandra到Kubernetes的过程

在 CentOS 7 中安装 MySQL 8 的教程详解
python基础之文件操作

Python面向对象程序设计之私有变量,私有方法原理与用法分析

python字典多键值及重复键值的使用方法(详解)
