【笔记】Go语言操作Mongodb数据库

前言

Go语言操作Mongodb数据库

下载依赖

1
go get go.mongodb.org/mongo-driver/mongo

获取连接

1
2
clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)

通过指定身份获取连接

<username>:用户名
<password>:密码

1
2
clientOptions := options.Client().ApplyURI("mongodb://<username>:<password>@127.0.0.1:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)

设置数据库连接池最大连接数

<num>:最大连接数,uint64类型数据

1
2
clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
client, err := mongo.Connect(context.TODO(), clientOptions.SetMaxConnecting(<num>))

Ping测试

1
err := client.Ping(context.TODO(), nil)

关闭连接

1
defer client.Disconnect(context.TODO())

对数据库的操作

获取数据库对象

1
db := client.Database("数据库名")

对集合的操作

获取集合对象

1
collection := db.Collection("数据表名")
1
collection := client.Database("数据库名").Collection("数据表名")

对文档的操作

新增文档

定义结构体

1
2
3
4
type User struct {
Name string
Age int
}
手动指定bson映射
1
2
3
4
type User struct {
Name string `bson:"name"`
Age int `bson:"age"`
}
排除bson映射
1
2
3
4
type User struct {
Name string `bson:"name"`
Age int `bson:"-"`
}

新增单个文档

1
collection.InsertOne(context.TODO(), User{Name: "字段名", Age: 值})
获取新增后的ID
1
res.InsertedID

新增多个文档

  • 新增文档,将[]interface{}类型的数据作为多个文档
1
collection.InsertMany(context.TODO(), []interface{}{User{Name: "字段名", Age: 值}, User{Name: "字段名", Age: 值}})
获取新增后的ID
1
res.InsertedIDs

删除文档

删除单个文档

1
2
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
res, err := collection.DeleteOne(context.TODO(), filter)

删除多个文档

1
2
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
res, err := collection.DeleteMany(context.TODO(), filter)

受影响的行数

1
res.DeletedCount

修改文档

修改单个文档

改为指定值
1
2
3
4
5
6
7
8
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
update := bson.D{
{
Key: "$set",
Value: bson.D{{Key: "字段名", Value: "修改后的字段值"}},
},
}
res, err := collection.UpdateOne(context.TODO(), filter, update)
  • 简写
1
2
3
4
5
6
7
8
9
10
filter := bson.D{{"查询字段名", "查询字段值"}}
update := bson.D{
{
"$set",
bson.D{
{"字段名", "修改后的字段值"}
},
},
}
res, err := collection.UpdateOne(context.TODO(), filter, update)
指定值自增
1
2
3
4
5
6
7
8
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
update := bson.D{
{
Key: "$inc",
Value: bson.D{{Key: "字段名", Value: 步长}},
},
}
res, err := collection.UpdateOne(context.TODO(), filter, update)

修改多个文档

改为指定值
1
2
3
4
5
6
7
8
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
update := bson.D{
{
Key: "$set",
Value: bson.D{{Key: "字段名", Value: "修改后的字段值"}},
},
}
res, err := collection.UpdateMany(context.TODO(), filter, update)
指定值自增
1
2
3
4
5
6
7
8
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
update := bson.D{
{
Key: "$inc",
Value: bson.D{{Key: "字段名", Value: 步长}},
},
}
res, err := collection.UpdateMany(context.TODO(), filter, update)

受影响的行数

1
res.ModifiedCount

查询文档

查询单个文档

1
2
3
var user User
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
err := collection.FindOne(context.TODO(), filter).Decode(&user)

查询多个文档

1
2
3
var users []User
filter := bson.D{{Key: "查询字段名", Value: "查询字段值"}}
err := collection.Find(context.TODO(), filter).Decode(&users)
指定查询选项
分页查询
1
2
3
4
5
6
var option *options.FindOptions = new(options.FindOptions)
option.SetSkip(int64((arg.PageNumber - 1) * arg.PageSize))
option.SetLimit(int64(arg.PageSize))

var users []User
err := collection.Find(context.TODO(), bson.D{}, option).Decode(&users)

查询文档总数

1
count, err := collection.CountDocuments(context.TODO(), bson.D{})

复合查询

模糊查询
1
filter := bson.M{"查询字段名": bson.M{"$regex": "关键字"}}
成员查询

$in:包含
$nin:不包含

1
2
filter := bson.M{"查询字段名": bson.M{"$in": []string{"查询字段值1", "查询字段值2"}}}
filter := bson.M{"查询字段名": bson.M{"$nin": []string{"查询字段值1", "查询字段值2"}}}
逻辑查询

$and:与
$or:或

1
2
filter := bson.M{"$and": bson.M{{"查询字段名1", "查询字段值1"}, {"查询字段名2", "查询字段值2"}}}
filter := bson.M{"$or": bson.M{{"查询字段名1", "查询字段值1"}, {"查询字段名2", "查询字段值2"}}}
比较查询

$gt:大于
$lt:小于
$gte:大于等于
$lte:小于等于
$ne:不等于

1
2
3
4
5
filter := bson.M{"查询字段名": bson.M{"$gt", 值}}
filter := bson.M{"查询字段名": bson.M{"$lt", 值}}
filter := bson.M{"查询字段名": bson.M{"$gte", 值}}
filter := bson.M{"查询字段名": bson.M{"$lte", 值}}
filter := bson.M{"查询字段名": bson.M{"$ne", 值}}
聚合查询

聚合函数名

$min:求最小值
$max:求最大值
$avg:求平均数
$first:获取当前排序的第一个文档
$last:获取当前排序的最后一个文档
$push:在结果数组中插入一个文档
$addToSet:在结果文档中插入一个文档,如果已经包含,不会重复插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
opts := options.Aggregate().SetMaxTime(2 * time.Second)
groupStage := bson.D{
{
"$group",
bson.D{
{"_id", "$major"},
{"查询结果字段名", bson.D{{"聚合函数类型", "$作为聚合函数参数的字段名"}}},
},
},
}
res, err := collection.Aggregate(context.TODO(), mongo.Pipeline{groupStage}, opts)
var 映射结果集 []bson.M
err = res.All(context.TODO(), &映射结果集)
fmt.Println(result)

完成

参考文献

哔哩哔哩——要叫我包子
稀土掘金——lomtom
CSDN——九思梦鹿
CSDN——chengqiang8340
阿里云开发者社区——高久峰