MongoDB
https://www.mongodb.com/download-center/community
打开客户端
mongo.exe
注意6.0版本不一样需要自行安装
Mongoshell
创建数据库
use go_db;
创建集合
db.createCollection("student");
添加MongoDB依赖
go get go.mongodb.org/mongo-driver/mongo
链接MongoDB
链接数据库
func connect(ctx contex.Contex, opts ...*options.ClientOptions)
Connect需要两个参数,一个context和一个options.ClientOption对象
var client *mongo.Client
func initDB(){
// 设置客户端选项
clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
// 链接MongoDB
var err error
client, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
fmt.Println("连接失败")
log.Panic(err)
}
// 检查连接
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Panic(err)
}
fmt.Println("连接成功")
}
创建数据标的连接对象
collectionStudent := client.Database("go_db").collection("student")
断开对象连接
client.Disconnect()
// 关闭
func main(){
initDB()
defer client.Disconnect(context.TODO())
}
err = client.Disconnect(context.TODO())
if err!=nil{
log.Fatal(err)
}
fmt.Println("MongoDB链接已关闭")
操作MongoDB数据库
插入单个文档
collection.InsertOne()
// 插入单条数据
func insertData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 初始化
s := Student {
Name: "张三",
Age: 18,
}
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 插入单条数据
ior, err := collection.InsertOne(context.TODO(),s)
if err != nil {
log.Fatal(err)
} else {
fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
}
}
插入多条文档
collection.InsertMany()
// 插入多条数据
func insertData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 初始化
s := Student {
Name: "张三",
Age: 18,
}
s1 := Student {
Name: "李四",
Age: 21,
}
// 声明成切片
stus := []interface{}{s,s1}
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 插入单条数据
ior, err := collection.InsertOne(context.TODO(),stus)
if err != nil {
log.Fatal(err)
} else {
fmt.Printf("ior.InsertedIDs: %v\n", ior.InsertedID)
}
}
更新单个文档
collection.UpdateOne()
// 修改单条数据
func insertData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// filter:包含查询操作符的文档,可用来选择要查询到的文档
// 查询到name=李四的文档
filter := bson.D{{Key:"name", Value:"李四"}}
// 修改name为张三 $inc添加 $set设置成
update := bson.D{
{Key: "$set", Value:bson.D{{Key:"name",Value:"张三"}}},
}
ur, err := collection.UpdateOne(context.TODO(),filter,update)
if err != nil {
log.Fatal(err)s
}
fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
}
更新多个文档
collection.UpdateMany()
// 修改单条数据
func insertData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 查询到name=张三的文档
filter := bson.D{{Key:"name", Value:"张三"}}
// 修改age加一岁 $inc添加 $set设置成
update := bson.D{
{Key: "$inc", Value:bson.D{{Key:"age",Value:1}}},
}
ur, err := collection.UpdateMany(context.TODO(),filter,update)
if err != nil {
log.Fatal(err)s
}
fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
}
删除单个文档
collenction.DeleteOne()
// 删除单个文档
func deleteData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 删除name=王五的数据
filter := bson.D{{Key:"name", Value:"王五"}}
dr, err := collection.DeleteOne(context.TODO(),filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ur.DeletedCount: %v\n", dr.DeletedCount)
}
删除多个文档
collection.DeleteMany()
// 删除多个文档
func deletManyeData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 删除name=王五的数据
filter := bson.D{{Key:"name", Value:"王五"}}
dr, err := collection.DeleteMany(context.TODO(),filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ur.DeletedCount: %v\n", dr.DeletedCount)
}
查询单个文档
collection.FindOne()
// 查询单个数据
func findData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 查找成功赋值
var s Student
// 查询name=王五
filter := bson.D{{Key:"name", Value:"王五"}}
err := collection.FindOne(context.TODO(),filter).Decode(&s)
if err != nil {
log.Fatal(err)
} else {
fmt.Printf(s)
}
}
查询多个文档
collenction.Find()
// 查询多个数据
func findData(){
// 链接mongodb
initDB()
// 成功后断开mongodb
defer client.Disconnect(context.TODO())
// 链接数据表对象
collection := client.Database("go_db").collection("student")
// 查询name=张三
filter := bson.D{{Key:"name", Value:"张三"}}
cursor, err := collection.Find(context.TODO(),filter)
if err != nil {
log.Fatal(err)
}
// 关闭上下文
defer cursor.Close(context.TODO())
// 定义切片
var students []student
err = cursor.All(context.TODO(), &students)
for _, student := range students {
fmt.Println(student)
}
}
复合查询
$regex 模糊查询
filter := bson.M{"name": bson.M{"$regex":"张"}}
in($in) 包含和 no in($nin)不包含
filter := bson.M{"name": bson.M{"$in":[]string{"张三","李四"}}}
and($and)和
filter := bson.M{"$and": []bson.M{"name":"张三"},{"age":18}}}
or($or)或
filter := bson.M{"$or": []bson.M{"name":"张三"},{"age":18}}}
比较函数
!=$ne>$gt<$lt>=$gte<=$lte
filter := bson.M{"age": bson.M{"$gt": 18}}
聚类聚合函数
$sum$avg$min$max$first$last$push在结果文档中插入一个值到一个数组中$addToSet在结果文档中插入一个值到数组,但不创建副本
定义最大时间
opts := options.Aggregate().SetMaxTime(2*time.Second)