首页 > 数据库 >golang-mongodb

golang-mongodb

时间:2022-08-19 13:14:14浏览次数:47  
标签:err mongodb fmt golang context Printf TODO

0、结构体

type Student struct {     // _id 不用带入
    Name string
    Age int
}

1、连接

  驱动 :github.com/mongodb/mongo-go-driver

  1、普通连接

client , err := mongo.Connect(
        context.TODO(),
        options.Client().ApplyURI("mongodb://192.168.6.249:27017"))
    if err != nil {
        fmt.Printf("mongodb connect failed, err : %s\n", err)
        return
    }
    defer func() {
        if err = client.Disconnect(context.TODO()); err != nil {
            fmt.Printf("mongodb disconnect failed, err : %s\n", err)
            return
        }
    }()

  2、连接池连接

 

2、插入

  1、插入单条

    collection := client.Database("erp").Collection("Student")
    // 插入一条
    s1 := Student{Age: 12, Name: "hello"}
    insertResult, err := collection.InsertOne(context.TODO(), s1)
    if err != nil {
        fmt.Printf("insert mongodb failed , err : %s\n", err)
        return
    }
    fmt.Println("insert a single document: ", insertResult)

  2、插入多条

    s2 := Student{Age: 13, Name: "world"}
    insertDocs := []interface{}{s1, s2}
    many, err := collection.InsertMany(context.TODO(), insertDocs)
    fmt.Println(many)  // &{[ObjectID("62fefa56a4e8957a0d611caf") ObjectID("62fefa56a4e8957a0d611cb0")]}

3、删除

  1、单个删除

// 删除单个文档 [有多条也仅仅只删除一条]
deleteResult1, err := collection.DeleteOne(context.TODO(), bson.M{"age": 12})
if err != nil {
    fmt.Printf("delete one doc failed, err : %s\n", err)
    return
}
fmt.Printf("delete %v doc", deleteResult1.DeletedCount)   // 删除文档的个数

  2、删除多个

// 删除所有文档
_, err = collection.DeleteMany(context.TODO(), bson.M{})
if err != nil {
fmt.Printf("delete many doc failed, err : %s\n", err)
return
}

 

4、查询

  1、单个查询

    var stu Student
    filter := bson.M{"age": 13}
    collection.FindOne(context.TODO(), filter).Decode(&stu)
    fmt.Printf("stu ==> %+v\n", stu)

  2、多个查询

// 查询多个文档
    findOptions := options.Find()
    findOptions.SetLimit(3)
    var results []*Student

    // 把 bson.D{{}} 作为一个 filter 来匹配所有文档
    cur, err :=collection.Find(context.TODO(), bson.D{{}}, findOptions)
    if err != nil {
        fmt.Printf("find mongodb failed, err : %s\n", err)
        return
    }
    // 查找多个文档返回一个光标
    // 遍历游标允许我们一次解码一个文档
    for cur.Next(context.TODO()) {
        // 创建一个值,将单个文档解码为该值
        var stu Student
        err := cur.Decode(&stu)
        if err != nil {
            fmt.Printf("mongodb decode, err : %s\n", err)
            return
        }
        results = append(results, &stu)
    }
    defer cur.Close(context.TODO())
    for _, v := range results {
        fmt.Printf("%v\n", v)
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

  

标签:err,mongodb,fmt,golang,context,Printf,TODO
From: https://www.cnblogs.com/dogHuang/p/16601648.html

相关文章

  • golang+mongodb+Aggregate管道查询
    在go语言中使用mongodb管道创建视图并条件分页查询使用bson.D{{}}包裹管道关键字条件例如:go语言中MongoDB配置qmngo查询总页数:bson.D{{"$count","total_cou......
  • MongoDB 单服务器创建用户并授权
    MongoDB单服务器创建用户并授权前言之前使用MongoDB时对于用户的认证和授权一直模模糊糊,各种教程看的半半拉拉,最后勉强能用。现在有时间了来总结一下。基础1.常见......
  • mongoDB学习笔记(正在完善中)
    打开mongoshellmongo添加超级管理员账户useadmin 切换到admin数据库db.createUser({user:'myadmin',pwd:'myadmin',roles:[{role:'userAdminAnyDatabase'......
  • redis-golang strings 操作
    本文来自于  github.com/go-redis/redis/v9的自带的测试代码commands_test1、Append(ctxcontext.Context,key,valuestring)//如果不存在key,就将keyval......
  • 解析PHP中常见的mongodb查询操作_PHP教程
    //栏位字串为$querys=array("name"=>"shian");//数值等于多少$querys=array("number"=>7);//数值大于多少$querys=array("number"=>array('$gt'=>5));//数值大......
  • mongodb 安装配置
    环境准备#cat/etc/redhat-releaseCentOSLinuxrelease7.9.2009(Core)vim/etc/security/limits.conf*softnproc655350*hardnproc655350*softnofile6......
  • 浮点数 mysql golang 时间序列
     1.6607259e+091660725877mysql>SELECTVal,CreateTs,CreateTsFROMTabWHEREDeviceId=156ANDOID=".1.3.6.1.4.1.28713.1.2.2.0" ANDCreateTs>=1660704714AN......
  • Golang打包windows、macos、linux下可执行文件
    windows.exe:#64bitGOOS=windowsGOARCH=amd64gobuild-obin/app-amd64.exeapp.go#32-bitGOOS=windowsGOARCH=386gobuild-obin/app-386.exeapp.goLinu......
  • 小白快速在cenos7系统搭建mongodb数据库及compass远程连接
    前言:本人的cenos系统是在腾讯云部署的云服务器,为个人网站提供服务,这里说明一下安装数据库遇到的问题和折腾记录。远程连接云服务器:这一步使用本地系统的可以跳过。之前......
  • golang
    Go与Java对比用途场景1.Java的用途用途一:服务器后端系统开发(web后端、微服务后端支付系统、业务系统、管理后台,各种后台交互的接口服务)。用途二:大数据框架的底层实现......