首页 > 数据库 >使用golang操作mongodb

使用golang操作mongodb

时间:2022-11-02 09:37:21浏览次数:71  
标签:detection mongo err mongodb golang coll context 操作 bson

背景

学习使用golang操作mongodb,主要是常见的增删改查。

代码

package main
 
import (
    "context"
    "fmt"
    "log"
 
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
 
    mog "go.mongodb.org/mongo-driver/mongo"
)
 
func main() {
    clientOptions := options.Client().ApplyURI("mongodb://qingteng:[email protected]:27017")
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        log.Fatal(err)
    }
 
    // 检测连接
    err = client.Ping(context.TODO(), nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
 
    // 获取collection
    detection_coll := client.Database("wisteria_detect").Collection("ids_detection")
 
    // 保存单条数据
    saveOne(detection_coll)
 
    // 批量保存数据
    batchSave(detection_coll)
 
    // 查询单条数据
    findOne(detection_coll)
 
    // 批量查询数据
    findMany(detection_coll)
 
    // 更新多条数据
    updateMany(detection_coll)
 
    // 删除单条数据
    deleteOne(detection_coll)
}
 
type DetectionDO struct {
    Id          string `bson:"_id"`
    ComId       string `bson:"comId"`
    DetectionId string `bson:"detectionId"`
}
 
/**
 * 插入单个
 */
func saveOne(detection_coll *mongo.Collection) {
    detection := DetectionDO{
        Id:          "100001",
        ComId:       "7070714a613939797533",
        DetectionId: "abc123456",
    }
    objId, err := detection_coll.InsertOne(context.TODO(), detection)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("_id:", objId.InsertedID)
}
 
/**
 * 批量插入
 */
func batchSave(detection_coll *mongo.Collection) {
    detection1 := DetectionDO{
        Id:          "100002",
        ComId:       "7070714a613939797533",
        DetectionId: "abc123456-2",
    }
    detection2 := DetectionDO{
        Id:          "100003",
        ComId:       "7070714a613939797533",
        DetectionId: "abc123456-3",
    }
 
    models := []mog.WriteModel{
        mog.NewInsertOneModel().SetDocument(detection1),
        mog.NewInsertOneModel().SetDocument(detection2),
    }
 
    opts := options.BulkWrite().SetOrdered(false)
    res, err := detection_coll.BulkWrite(context.TODO(), models, opts)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("insertCount:", res.InsertedCount)
}
 
/**
 * 查询单个
 */
func findOne(detection_coll *mongo.Collection) {
    filter := bson.D{{Key: "comId", Value: "7070714a613939797533"}, {Key: "detectionId", Value: "684b8788169c481e9dff73889b170072zh1pxms0"}}
 
    var result map[string]interface{}
    err := detection_coll.FindOne(context.TODO(), filter).Decode(&result)
    if err != nil {
        log.Fatal(err)
    }
    // fmt.Println(result)
}
 
/**
 * 批量查询
 */
func findMany(detection_coll *mongo.Collection) {
    filter := bson.D{{Key: "comId", Value: "7070714a613939797533"}}
 
    cur, err := detection_coll.Find(context.TODO(), filter)
    if err != nil {
        log.Fatal(err)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
 
    var list []*DetectionDO
    err = cur.All(context.Background(), &list)
    if err != nil {
        log.Fatal(err)
    }
 
    _ = cur.Close(context.Background())
 
    for _, one := range list {
        fmt.Printf("_id:%s, comId:%s, detectionId:%s\n", one.Id, one.ComId, one.DetectionId)
    }
}
 
/**
 * 更新
 */
func updateMany(detection_coll *mongo.Collection) {
    detectionIds := []string{"d42161747d9547b3aaee8f6464792c40vcnzd8q6", "684b8788169c481e9dff73889b170072zh1pxms0", "bed744bcae2d47d5a682369d76acda52jgpphi5y"}
    filter := bson.D{{Key: "comId", Value: "7070714a613939797533"}, {Key: "detectionId", Value: bson.D{{Key: "$in", Value: detectionIds}}}}
 
    update := bson.D{
        {Key: "$set", Value: bson.D{
            {Key: "detectionName", Value: "使用golang测试批量更新咯"},
        }},
    }
    result, err := detection_coll.UpdateMany(context.TODO(), filter, update)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("modifiedCount:%d\n", result.ModifiedCount)
}
 
/**
 * 删除
 */
func deleteOne(detection_coll *mongo.Collection) {
    filter := bson.D{{Key: "comId", Value: "7070714a613939797533"}, {Key: "detectionId", Value: "684b8788169c481e9dff73889b170072zh1pxms0"}}
    result, err := detection_coll.DeleteOne(context.TODO(), filter)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("deleteCount:%d\n", result.DeletedCount)
}

说明:

标签:detection,mongo,err,mongodb,golang,coll,context,操作,bson
From: https://www.cnblogs.com/xuwenjin/p/16849917.html

相关文章

  • MongoDB随记
    正常情况下MongoDB的db就是mysql里的库;而collection就是mysql里的表(MongoDB的表名可以是用.分隔,比如aaa.bbb;但是注意自定义表不能以system.aaa格式);然后可视化工具在表名......
  • Javascript进阶笔记 - DOM操作CSS样式
    DOM操作CSS样式目录DOM操作CSS样式1.操作样式2.获取当前样式3.其它样式相关属性1.操作样式可以通过JS修改元素的内联样式语法:元素.style.样式名=样式值注意:......
  • 创建对象,属性操作
    创建对象letobj={};letobj=newObject();letobj=Object.create(null);//不能不传值,null表示空值letobj=Object.assign(obj1,obj2,obj3);//**操作obj1......
  • 【Java编程思想读书笔记】第二章:一切都是对象+第三章:操作符+第四章:控制执行流程
    参考书目:《Java编程思想》(第四版)友链:​​【读书笔记】Java重要知识点整理与汇总​​阅读《Java编程思想》(第四版)一书收获颇多,之所以想通过用博客记笔记的方式来读书,是因为......
  • 039.StringBuilder的常规操作和链式操作
    1.Java编译器对String做了特殊处理,虽然可以直接拼接字符串,但是,在循环中,每次循环都会创建新的字符串对象,然后扔掉旧的字符串。这样,绝大部分字符串都是临时对象,不但浪费内存......
  • Oracle 数据库忘记sys与system管理员密码重置操作方法
    首先打开cmd执行123orapwdfile=C:\app\PWDorcl.orapassword=orclorclC:\app\PWDorcl.ora是你要存放的路径文件Password=orclorcl是你要改的密码......
  • 优雅处理Golang中的异常
    我们在使用Golang时,不可避免会遇到异常情况的处理,与Java、Python等语言不同的是,Go中并没有try...catch...这样的语句块,我们知道在Java中使用try...catch...这种模式不仅能......
  • Linux学习笔记(第二篇)目录操作命令
    ​​Linux学习笔记(第零篇)计算机基础​​Linux学习笔记(第零篇)Linux文件系统及ShellLinux学习笔记(第一篇)零散命令Linux学习笔记(第二篇)目录操作命令Linux学习笔记(第三篇)文件操......
  • Linux学习笔记(第四篇)文件内容操作命令+正则表达式+重定向和管道
    ​​Linux学习笔记(第零篇)计算机基础​​Linux学习笔记(第零篇)Linux文件系统及ShellLinux学习笔记(第一篇)零散命令Linux学习笔记(第二篇)目录操作命令Linux学习笔记(第三篇)文件操......
  • Linux学习笔记(第三篇)文件操作命令
    ​​Linux学习笔记(第零篇)计算机基础​​Linux学习笔记(第零篇)Linux文件系统及ShellLinux学习笔记(第一篇)零散命令Linux学习笔记(第二篇)目录操作命令Linux学习笔记(第三篇)文件操......