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

Go 语言操作 MongoDb

文章目录

  • 连接数据库
  • 插入数据库
    • 插入一条数据
    • 批量插入数据
  • 查询数据
  • 用 BSON 进行复合查询
    • 聚合查询
  • 更新数据
  • 删除数据

连接数据库

package main

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}
func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

func main() {
	//连接数据库
	var (
		client     = MgoCli()
		db         *mongo.Database
		collection *mongo.Collection
	)
	db = client.Database("my_db")
	collection = db.Collection("my_collection")
	collection = collection
}

插入数据库

插入一条数据

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

// 插入一条数据
type ExecTime struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type LogRecord struct {
	JobName string `bson:"jobName"`
	Command string `bson:"command"`
	Err     string `bson:"err"`
	Content string `bson:"content"`
	Tp      ExecTime
}

func main() {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		iResult    *mongo.InsertOneResult
		id         primitive.ObjectID
	)
	collection = client.Database("my_db").Collection("my_collection")

	logRecord := LogRecord{
		JobName: "job1",
		Command: "echo 1",
		Err:     "",
		Content: "1",
		Tp: ExecTime{
			StartTime: time.Now().Unix(),
			EndTime:   time.Now().Unix() + 10,
		},
	}
	if iResult, err = collection.InsertOne(context.TODO(), logRecord); err != nil {
		fmt.Println(err)
		return
	}
	id = iResult.InsertedID.(primitive.ObjectID)
	fmt.Println("自增 ID", id.Hex())
}

批量插入数据

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

// 插入一条数据
type ExecTime struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type LogRecord struct {
	JobName string `bson:"jobName"`
	Command string `bson:"command"`
	Err     string `bson:"err"`
	Content string `bson:"content"`
	Tp      ExecTime
}

func main() {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		result     *mongo.InsertManyResult
		id         primitive.ObjectID
	)
	collection = client.Database("my_db").Collection("test")

	result, err = collection.InsertMany(context.TODO(), []interface{}{
		LogRecord{
			JobName: "job1",
			Command: "echo 1",
			Err:     "",
			Content: "1",
			Tp: ExecTime{
				StartTime: time.Now().Unix(),
				EndTime:   time.Now().Unix() + 10,
			},
		},
		LogRecord{
			JobName: "job1",
			Command: "echo 1",
			Err:     "",
			Content: "1",
			Tp: ExecTime{
				StartTime: time.Now().Unix(),
				EndTime:   time.Now().Unix() + 10,
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if result == nil {
		log.Fatal("result nil")
	}
	for _, v := range result.InsertedIDs {
		id = v.(primitive.ObjectID)
		fmt.Println("自增 ID", id.Hex())

	}
}

查询数据

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

// 插入一条数据
type ExecTime struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type LogRecord struct {
	JobName string `bson:"jobName"`
	Command string `bson:"command"`
	Err     string `bson:"err"`
	Content string `bson:"content"`
	Tp      ExecTime
}

type FindByJobName struct {
	JobName string `bson:"jobName"`
}

func main() {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		cursor     *mongo.Cursor
	)
	collection = client.Database("my_db").Collection("table1")
	cond := FindByJobName{JobName: "job multil"}
	findOptions := options.Find().SetSkip(0).SetLimit(2)
	if cursor, err = collection.Find(context.TODO(), cond, findOptions); err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err = cursor.Close(context.TODO()); err != nil {
			log.Fatal(err)
		}
	}()
	for cursor.Next(context.TODO()) {
		var lr LogRecord
		if cursor.Decode(&lr) != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(lr)
	}
	var results []LogRecord
	if err = cursor.All(context.TODO(), &results); err != nil {
		log.Fatal(err)
	}
	for _, result := range results {
		fmt.Println(result)
	}
}

用 BSON 进行复合查询

聚合查询

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

func main() {
	client := MgoCli()
	collection := client.Database("my_db").Collection("table1")
	groupStage := mongo.Pipeline{
		bson.D{
			{"$group", bson.D{
				{"_id", "$jobName"},
				{"countJob", bson.D{
					{"$sum", 1},
				}},
			}},
		},
	}

	cursor, err := collection.Aggregate(context.TODO(), groupStage)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		err = cursor.Close(context.TODO()) // 修正关闭游标的错误处理
		if err != nil {
			log.Fatal(err)
		}
	}()

	var results []bson.M
	err = cursor.All(context.TODO(), &results)
	if err != nil {
		log.Fatal(err)
	}

	for _, result := range results {
		fmt.Println(result)
	}
}

更新数据

package main

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

type UpdateByJobName struct {
	Command string `bson:"command"`
	Content string `bson:"content"`
}

func main() {
	var (
		client     = MgoCli()
		collection *mongo.Collection
		err        error
		uResult    *mongo.UpdateResult
	)
	collection = client.Database("my_db").Collection("table1")
	filter := bson.M{"jobName": "job multil"}
	// bson.M{"$inc",bson.M{"age",-1,}}
	//bson.M{"$push",bson.M{"interests","Golang",}}
	//bson.M{"$pull",bson.M{"interests","Golang",}}
	update := bson.M{"$set": UpdateByJobName{
		Command: "byModel",
		Content: "model",
	}}
	if uResult, err = collection.UpdateMany(context.TODO(), filter, update); err != nil {
		log.Fatal(err)
	}
	log.Println(uResult.MatchedCount)
}

删除数据


package main

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

type DeleteCond struct {
	BeforeCond TimeBeforeCond `bson:"tp.startTime"`
}

// startTime小于某时间,使用这种方式可以对想要进行的操作($set、$group等)提前定义
type TimeBeforeCond struct {
	BeforeTime int64 `bson:"$lt"`
}

func main() {
	var (
		client     = MgoCli()
		collection *mongo.Collection
		err        error
		uResult    *mongo.DeleteResult
		delCond    *DeleteCond
	)
	collection = client.Database("my_db").Collection("table1")

	//删除jobName为job0的数据
	delCond = &DeleteCond{
		BeforeCond: TimeBeforeCond{
			BeforeTime: time.Now().Unix()}}
	if uResult, err = collection.DeleteMany(context.TODO(),
		delCond); err != nil {
		log.Fatal(err)
	}
	log.Println(uResult.DeletedCount)
}

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}

func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

// 分组
type Group struct {
	Group interface{} `bson:"$group"`
}

// 求和
type Sum struct {
	Sum interface{} `bson:"$sum"`
}

func main() {
	var (
		client     = MgoCli()
		collection *mongo.Collection
		err        error
		cursor     *mongo.Cursor
	)
	collection = client.Database("my_db").Collection("table1")

	groupStage := []Group{}
	groupStage = append(groupStage, Group{
		Group: bson.D{
			{"_id", "$jobName"},
			{"countJob", Sum{Sum: 1}},
		},
	})

	if cursor, err = collection.Aggregate(context.TODO(),
		groupStage); err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err = cursor.Close(context.TODO()); err != nil {
			log.Fatal(err)
		}
	}()
	var results []bson.M
	if err = cursor.All(context.TODO(), &results); err != nil {
		log.Fatal(err)
	}
	for _, result := range results {
		fmt.Println(result)
	}
}


http://www.kler.cn/a/106786.html

相关文章:

  • 大模型在蓝鲸运维体系应用——蓝鲸运维开发智能助手
  • QT<30> Qt中使鼠标变为转圈忙状态
  • HarmonyOS NEXT应用开发实战 ( 应用的签名、打包上架,各种证书详解)
  • FlinkPipelineComposer 详解
  • MySQL【三】
  • 【WRF理论第十二期】输出文件:wrfout 和 wrfrst
  • 23 行为型模式-迭代器模式
  • node实战——搭建带swagger接口文档的后端koa项目(node后端就业储备知识)
  • 使用pycharm远程调试
  • MySQL视图的使用和优化
  • Spring Cloud之微服务
  • Milvus 入门教程
  • 机器学习笔记:逆置换
  • 鸿蒙ArkUI-X跨端应用开发,一套代码构建多平台应用
  • Day38 Qchart绘制灰度直方图
  • C#序列化与反序列化详解
  • 04-流媒体-ffmpeg.c源码分析
  • Corel Products Keygen-X-FORCE 2023(Corel会声会影2023注册机)
  • 【计算机网络笔记】Cookie技术
  • B F C
  • 浏览器事件循环 (event loop)
  • Centos安装gitlabce
  • Go学习第十章——文件操作,Json和测试
  • CVE-2021-41773/42013 apache路径穿越漏洞
  • Unity - 导出的FBX模型,无法将 vector4 保存在 uv 中(使用 Unity Mesh 保存即可)
  • 【蓝桥每日一题]-前缀和与差分(保姆级教程 篇1)