Go 语言操作 MongoDb

文章目录

连接数据库

cpp 复制代码
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
}

插入数据库

插入一条数据

cpp 复制代码
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())
}

批量插入数据

cpp 复制代码
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())

	}
}

查询数据

cpp 复制代码
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 进行复合查询

聚合查询

cpp 复制代码
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)
	}
}

更新数据

cpp 复制代码
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)
}

删除数据

cpp 复制代码
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)
}
cpp 复制代码
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)
	}
}
相关推荐
陌小呆^O^9 分钟前
Cmakelist.txt之win-c-udp-server
c语言·开发语言·udp
Gu Gu Study16 分钟前
枚举与lambda表达式,枚举实现单例模式为什么是安全的,lambda表达式与函数式接口的小九九~
java·开发语言
时光の尘31 分钟前
C语言菜鸟入门·关键字·float以及double的用法
运维·服务器·c语言·开发语言·stm32·单片机·c
以后不吃煲仔饭1 小时前
Java基础夯实——2.7 线程上下文切换
java·开发语言
进阶的架构师1 小时前
2024年Java面试题及答案整理(1000+面试题附答案解析)
java·开发语言
前端拾光者1 小时前
利用D3.js实现数据可视化的简单示例
开发语言·javascript·信息可视化
程序猿阿伟1 小时前
《C++ 实现区块链:区块时间戳的存储与验证机制解析》
开发语言·c++·区块链
傻啦嘿哟1 小时前
如何使用 Python 开发一个简单的文本数据转换为 Excel 工具
开发语言·python·excel
大数据编程之光1 小时前
Flink Standalone集群模式安装部署全攻略
java·大数据·开发语言·面试·flink
初九之潜龙勿用1 小时前
C#校验画布签名图片是否为空白
开发语言·ui·c#·.net