当前位置: 首页 > news >正文

MongoDB学习笔记

MongoDB

https://www.mongodb.com/download-center/community

打开客户端

mongo.exe

注意6.0版本不一样需要自行安装Mongoshell

MongoDB Shell Download | MongoDB

创建数据库

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)

MongoDB

相关文章:

  • Python|基于DeepSeek大模型,自动生成语料数据(10)
  • IDE集成开发环境MyEclipse中安装SVN
  • 每日一题——763. 划分字母区间
  • 【面试】Java 并发
  • 基于stm32的模拟电磁曲射炮研究
  • mysql的Innodb最大支持的索引长度是多少,以及索引长度怎么计算
  • Leetcode 3479. Fruits Into Baskets III
  • 蓝桥杯第二天:2023省赛C 1题 分糖果
  • unordered_set 的常用函数
  • 【python】Flask web框架
  • ble.sh 的安装和用法
  • 如何在SpringBoot中灵活使用异步事件?
  • C++—vector类的使用及模拟实现
  • Windows 11下Git Bash执行cURL脚本400问题、CMD/PowerShell不能执行多行文本等问题记录及解决方案
  • 进程(上)【Linux操作系统】
  • Web基础:HTML快速入门
  • doris:Elasticsearch
  • 六轴传感器ICM-20608
  • 10. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Ocelot 网关--认证
  • VBA 数据库同一表的当前行与其他行的主键重复判断实现方案1
  • 手机百度怎么解除禁止访问网站/东莞服务好的营销型网站建设
  • 怎么做分销平台/优化防控举措
  • 怎么把网站做成软件/推广竞价托管公司
  • 网上哪些网站可以做设计项目/如何做好网络营销推广
  • 发票项目网站建设费/seo推广费用
  • 复制推广链接/一站传媒seo优化