MongoDB学习条记

十念  论坛元老 | 2025-3-12 02:52:08 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1012|帖子 1012|积分 3036

MongoDB

  1. https://www.mongodb.com/download-center/community
复制代码
打开客户端

  1. mongo.exe
复制代码
  留意6.0版本不一样需要自行安装Mongoshell
  MongoDB Shell Download | MongoDB
  创建数据库

  1. use go_db;
复制代码
创建集合

  1. db.createCollection("student");
复制代码
添加MongoDB依赖

  1. go get go.mongodb.org/mongo-driver/mongo
复制代码
链接MongoDB

链接数据库

  1. func connect(ctx contex.Contex, opts ...*options.ClientOptions)
复制代码
Connect需要两个参数,一个context和一个options.ClientOption对象
  1. var client *mongo.Client
  2. func initDB(){
  3.     // 设置客户端选项
  4.    clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
  5.    // 链接MongoDB
  6.    var err error
  7.    client, err = mongo.Connect(context.TODO(), clientOptions)
  8.    if err != nil {
  9.        fmt.Println("连接失败")
  10.        log.Panic(err)
  11.    }
  12.    
  13.    // 检查连接
  14.    err = client.Ping(context.TODO(), nil)
  15.    if err != nil {
  16.        log.Panic(err)
  17.    }
  18.    fmt.Println("连接成功")
  19. }
复制代码
创建数据标的连接对象

  1. collectionStudent := client.Database("go_db").collection("student")
复制代码
断开对象连接

  1. client.Disconnect()
复制代码
  1. // 关闭
  2. func main(){
  3.     initDB()
  4.     defer client.Disconnect(context.TODO())
  5. }
复制代码
  1. err = client.Disconnect(context.TODO())
  2. if err!=nil{
  3. log.Fatal(err)
  4. }
  5. fmt.Println("MongoDB链接已关闭")
复制代码
操纵MongoDB数据库

插入单个文档

  1. collection.InsertOne()
复制代码
  1. // 插入单条数据
  2. func insertData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.    
  8.     // 初始化
  9.     s := Student {
  10.         Name: "张三",
  11.         Age: 18,
  12.     }
  13.     // 链接数据表对象
  14.     collection := client.Database("go_db").collection("student")
  15.     // 插入单条数据
  16.     ior, err := collection.InsertOne(context.TODO(),s)
  17.     if err != nil {
  18.         log.Fatal(err)
  19.     } else {
  20.         fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
  21.     }
  22. }
复制代码
插入多条文档

  1. collection.InsertMany()
复制代码
  1. // 插入多条数据
  2. func insertData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.    
  8.     // 初始化
  9.     s := Student {
  10.         Name: "张三",
  11.         Age: 18,
  12.     }
  13.     s1 := Student {
  14.         Name: "李四",
  15.         Age: 21,
  16.     }
  17.     // 声明成切片
  18.     stus := []interface{}{s,s1}   
  19.     // 链接数据表对象
  20.     collection := client.Database("go_db").collection("student")
  21.     // 插入单条数据
  22.     ior, err := collection.InsertOne(context.TODO(),stus)
  23.     if err != nil {
  24.         log.Fatal(err)
  25.     } else {
  26.         fmt.Printf("ior.InsertedIDs: %v\n", ior.InsertedID)
  27.     }
  28. }
复制代码
更新单个文档

  1. collection.UpdateOne()
复制代码
  1. // 修改单条数据
  2. func insertData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.     // 链接数据表对象
  8.     collection := client.Database("go_db").collection("student")
  9.    
  10.     // filter:包含查询操作符的文档,可用来选择要查询到的文档
  11.     // 查询到name=李四的文档
  12.     filter := bson.D{{Key:"name", Value:"李四"}}
  13.     // 修改name为张三 $inc添加 $set设置成
  14.     update := bson.D{
  15.         {Key: "$set", Value:bson.D{{Key:"name",Value:"张三"}}},
  16.     }
  17.     ur, err := collection.UpdateOne(context.TODO(),filter,update)
  18.     if err != nil {
  19.         log.Fatal(err)s
  20.     }
  21.     fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
  22. }
复制代码
更新多个文档

  1. collection.UpdateMany()
复制代码
  1. // 修改单条数据
  2. func insertData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.     // 链接数据表对象
  8.     collection := client.Database("go_db").collection("student")
  9.    
  10.     // 查询到name=张三的文档
  11.     filter := bson.D{{Key:"name", Value:"张三"}}
  12.     // 修改age加一岁 $inc添加 $set设置成
  13.     update := bson.D{
  14.         {Key: "$inc", Value:bson.D{{Key:"age",Value:1}}},
  15.     }
  16.     ur, err := collection.UpdateMany(context.TODO(),filter,update)
  17.     if err != nil {
  18.         log.Fatal(err)s
  19.     }
  20.     fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
  21. }
复制代码
删除单个文档

  1. collenction.DeleteOne()
复制代码
  1. // 删除单个文档
  2. func deleteData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.     // 链接数据表对象
  8.     collection := client.Database("go_db").collection("student")
  9.     // 删除name=王五的数据
  10.     filter := bson.D{{Key:"name", Value:"王五"}}
  11.     dr, err := collection.DeleteOne(context.TODO(),filter)
  12.     if err != nil {
  13.         log.Fatal(err)
  14.     }
  15.     fmt.Printf("ur.DeletedCount: %v\n", dr.DeletedCount)
  16. }
复制代码
删除多个文档

  1. collection.DeleteMany()
复制代码
  1. // 删除多个文档
  2. func deletManyeData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.     // 链接数据表对象
  8.     collection := client.Database("go_db").collection("student")
  9.     // 删除name=王五的数据
  10.     filter := bson.D{{Key:"name", Value:"王五"}}
  11.     dr, err := collection.DeleteMany(context.TODO(),filter)
  12.     if err != nil {
  13.         log.Fatal(err)
  14.     }
  15.     fmt.Printf("ur.DeletedCount: %v\n", dr.DeletedCount)
  16. }
复制代码
查询单个文档

  1. collection.FindOne()
复制代码
  1. // 查询单个数据
  2. func findData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.     // 链接数据表对象
  8.     collection := client.Database("go_db").collection("student")
  9.     // 查找成功赋值
  10.     var s Student
  11.     // 查询name=王五
  12.     filter := bson.D{{Key:"name", Value:"王五"}}
  13.     err := collection.FindOne(context.TODO(),filter).Decode(&s)
  14.     if err != nil {
  15.         log.Fatal(err)
  16.     } else {
  17.         fmt.Printf(s)
  18.     }
  19. }
复制代码
查询多个文档

  1. collenction.Find()
复制代码
  1. // 查询多个数据
  2. func findData(){
  3.     // 链接mongodb
  4.     initDB()
  5.     // 成功后断开mongodb
  6.     defer client.Disconnect(context.TODO())
  7.     // 链接数据表对象
  8.     collection := client.Database("go_db").collection("student")
  9.     // 查询name=张三
  10.     filter := bson.D{{Key:"name", Value:"张三"}}
  11.     cursor, err := collection.Find(context.TODO(),filter)
  12.     if err != nil {
  13.         log.Fatal(err)
  14.     }
  15.     // 关闭上下文
  16.     defer cursor.Close(context.TODO())
  17.     // 定义切片
  18.     var students []student
  19.     err = cursor.All(context.TODO(), &students)
  20.    
  21.     for _, student := range students {
  22.         fmt.Println(student)
  23.     }
  24. }
复制代码
复合查询

$regex 模糊查询

  1. filter := bson.M{"name": bson.M{"$regex":"张"}}
复制代码
in($in) 包含和 no in($nin)不包含

  1. filter := bson.M{"name": bson.M{"$in":[]string{"张三","李四"}}}
复制代码
and($and)和

  1. filter := bson.M{"$and": []bson.M{"name":"张三"},{"age":18}}}
复制代码
or($or)或

  1. filter := bson.M{"$or": []bson.M{"name":"张三"},{"age":18}}}
复制代码
比力函数



  • != $ne
  • > $gt
  • < $lt
  • >= $gte
  • <= $lte
  1. filter := bson.M{"age": bson.M{"$gt": 18}}
复制代码
聚类聚合函数



  • $sum
  • $avg
  • $min
  • $max
  • $first
  • $last
  • $push 在结果文档中插入一个值到一个数组中
  • $addToSet 在结果文档中插入一个值到数组,但不创建副本
界说最大时间
  1. opts := options.Aggregate().SetMaxTime(2*time.Second)
复制代码
MongoDB

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

十念

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表