golang mongodb增删改查相关操作

package main

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

type DetectionDo struct {
	Id          string `bson:"id"`
	ComId       string `bson:"comId"`
	DetectionId string `bson:"detectionId"`
}

var ClientOptions *options.ClientOptions
var Client *mongo.Client

func init() {
	InitMongodb() //初始化mongodb
}
func InitMongodb() {
	ClientOptions := options.Client().ApplyURI("mongodb://admin:admin@192.168.75.6:27017")
	Client, err := mongo.Connect(context.TODO(), ClientOptions)
	if err != nil {
		fmt.Println(err)
	}
	err = Client.Ping(context.TODO(), nil)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("mongodb 连接成功")
}

func main() {

	//获取collection//指定mongodb对象
	detectionColl := Client.Database("wisteria_detect").Collection("ids_detection")

	//保存单条数据
	saveOne(detectionColl)
	//批量保存数据
	batchSave(detectionColl)
	//查询单个数据
	findOne(detectionColl)
	//批量查询
	findMany(detectionColl)
	//更新操作
	updateMany(detectionColl)
	//删除操作/
	deleteOne(detectionColl)
	//批量删除
	deleteMany(detectionColl)

}

func deleteMany(detectionColl *mongo.Collection) {
	filter := bson.D{{
		Key:   "comId",
		Value: "7070714a613939797533",
	}}
	n := 0
	for {
		many, err := detectionColl.DeleteOne(context.TODO(), filter)
		//这里使用的是单一循环删除.在大数据量删除过程中可能会出现mongodb负载飙升的情况
		//还可以使用类似于批量插入的手法.将指定id编写一个切片,然后使用$in进行单一数据指定进行数据删除
		if err != nil {
			fmt.Println(err)
		}
		n += int(many.DeletedCount)
		if many.DeletedCount == 0 {
			break
		}
	}
	fmt.Printf("deleteManyCount:%d\n", n)
}

// 删除操作
func deleteOne(detectionColl *mongo.Collection) {
	filter := bson.D{{
		Key:   "comId",
		Value: "7070714a613939797533",
	}, {
		Key:   "detectionName",
		Value: "到底更新了些啥?????",
	}}
	one, err := detectionColl.DeleteOne(context.TODO(), filter)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("deleteCount:%d\n", one.DeletedCount)
}

// 更新操作
func updateMany(detectionColl *mongo.Collection) {
	detectionIds := []string{"abc123456", //这里需要先定义好需要更新的所有内容的字段值.更新过程中用作条件筛选操作
		"684b8788169c481e9dff73889b170072zh1pxms0",
		"bed744bcae2d47d5a682369d76acda52jgpphi5y"}
	filter := bson.D{{ //指定更新的筛选条件,这个条件可以是多个.这里使用的是comId= 7070714a613939797533 ,和deteltionId = xxx一个bson值
		Key:   "comId",
		Value: "7070714a613939797533",
	}, {
		Key:   "detectionId",
		Value: bson.D{{Key: "$in", Value: detectionIds}},
	}}

	update := bson.D{{ //这里需要指定更新操作$set表示更新操作.
		Key: "$set",
		Value: bson.D{{ //这里指定更新操作的键值.
			Key:   "detectionName",
			Value: "到底更新了些啥?????",
		}},
	}}
	many, err := detectionColl.UpdateMany(context.TODO(), filter, update)
	//filter是指定要修改数据的条件,
	// update是修改的字段和值本身.如果字段你没有的话就直接创建,,如果有的话就进行对应字段的值进行修改.
	//更新完成后返回更新行数和id等相关信息.
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(many.ModifiedCount)
	fmt.Println(many.UpsertedID)
}

// 查询多个
func findMany(detectionColl *mongo.Collection) {
	d := bson.D{{
		Key:   "comId",
		Value: "7070714a613939797533",
	}} //指定使用查询字段作为查询条件.这里指定的是comId字段的值作为查询条件.
	cur, err := detectionColl.Find(context.TODO(), d) //根据指定好的查询条件d进行查询操作.最终返回的结果
	if err != nil {
		fmt.Println(err)
	}
	var list []*DetectionDo
	err = cur.All(context.Background(), &list) //将查询出来的结果保存到一个detectionDo类型的切片中.用于后续的遍历操作.
	if err != nil {
		fmt.Println(err)
	}

	defer cur.Close(context.Background()) //关闭连接对象
	for _, one := range list {
		fmt.Printf("_id:%s,comId:%s,detectionId:%s\n", one.Id, one.ComId, one.DetectionId)

	}
}

// 查询单个
func findOne(detectionColl *mongo.Collection) {
	filter := bson.D{{ //创建一个bson.d指定查询字段的键值,这个键值可以是多个.
		Key:   "comId",
		Value: "7070714a613939797533",
	}, {Key: "detectionId", Value: "abc123456"}}
	result := make(map[string]interface{})                               //
	err := detectionColl.FindOne(context.TODO(), filter).Decode(&result) //将查询结果放到一个指定的map中,进行后续处理
	if err != nil {
		fmt.Println(err)
	}
	for k, v := range result {
		fmt.Println(k, v)
	}
}

// 批量插入数据
func batchSave(detectionColl *mongo.Collection) {
	detection1 := DetectionDo{
		Id:          "100002",
		ComId:       "7070714a613939797533",
		DetectionId: "abc123456-2",
	}
	detection2 := DetectionDo{
		Id:          "100003",
		ComId:       "7070714a613939797533",
		DetectionId: "abc123456-3",
	}
	s1 := []DetectionDo{}
	s1 = append(s1, detection1, detection2)
	for _, v := range s1 {
		one, err := detectionColl.InsertOne(context.TODO(), v) //这里我用的是循环单次插入操作.
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println("插入多条数据", one.InsertedID)
	}
}

func saveOne(detection_coll *mongo.Collection) {
	detection := DetectionDo{
		Id:          "100001",
		ComId:       "7070714a613939797533",
		DetectionId: "abc123456",
	}
	one, err := detection_coll.InsertOne(context.TODO(), detection)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Id", one.InsertedID)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值