go 预处理 mongodb 的insert

1.如何预处理

如果我们想预处理mongo的数据创建方法,如添加 公共字段 public1,public2

可以重写collection来实现

具体如下:

package mongo

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

type Collection struct {
	*mongo.Collection
}

func (col *Collection) InsertOne(ctx context.Context, document interface{},
	opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
	b, err := bson.Marshal(document)
	if err != nil {
		return nil, err
	}
	newDoc := bson.M{}
	err = bson.Unmarshal(b, &newDoc)
	if err != nil {
		return nil, err
	}
	newDoc["public1"] = "public1"
	newDoc["public2"] = "public2"
	return col.Collection.InsertOne(ctx, newDoc, opts...)
}

func (col *Collection) InsertMany(ctx context.Context, documents []interface{},
	opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error) {

	for i, v := range documents {
		b, err := bson.Marshal(v)
		if err != nil {
			return nil, err
		}
		newDoc := bson.M{}
		err = bson.Unmarshal(b, &newDoc)
		if err != nil {
			return nil, err
		}
		newDoc["public1"] = "public1"
		newDoc["public2"] = "public2"
		documents[i] = newDoc
	}
	return col.Collection.InsertMany(ctx, documents, opts...)
}

2.如何使用?

下面写了一个go test 来举例如何使用

package mongo

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

func cli() *mongo.Client {
	// 设置客户端选项
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接 MongoDB
	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)
	}
	return client
}

func TestCreateMongoCollection(t *testing.T) {
	c := cli()
	collectionStudent := &Collection{c.Database("mongodb_study").Collection("student")}
	collectionStudent2 := &Collection{c.Database("mongodb_study").Collection("student2")}
	ctx := context.TODO()
	collectionStudent.DeleteMany(ctx, bson.M{})
	collectionStudent2.DeleteMany(ctx, bson.M{})

	type Student struct {
		Name string
		Age  int
	}
	//1.插入一条数据
	stu1 := Student{"李四", 133}
	_, err := collectionStudent.InsertOne(ctx, stu1)
	if err != nil {
		log.Println(err)
	}
	//2.插入多条文档
	students := []interface{}{Student{"张三", 12}, Student{"王五", 16}}
	_, err = collectionStudent.InsertMany(ctx, students)
	if err != nil {
		log.Println(err)
	}
	//3.更新单个文档,如果有多个满足条件的,只更新第一条
	filter := bson.D{{"name", "张三"}}
	// 修改name 为hhhh
	update := bson.D{
		{"$set", bson.D{{"name", "张三三"}}},
	}
	collectionStudent.UpdateOne(ctx, filter, update)

	//4.开启事务
	session, err := c.StartSession()
	if err != nil {
		panic(err)
	}
	defer session.EndSession(context.TODO())
	wc := writeconcern.New(writeconcern.WMajority())
	txnOptions := options.Transaction().SetWriteConcern(wc)
	session.WithTransaction(context.TODO(), func(ctx mongo.SessionContext) (interface{}, error) {
		students := []interface{}{Student{"张三", 15}, Student{"王五", 17}}
		_, err := collectionStudent.InsertMany(ctx, students)
		if err != nil {
			fmt.Println("InsertMany err:", err)
		}
		_, err = collectionStudent2.InsertMany(ctx, students)
		if err != nil {
			fmt.Println("InsertMany2 err:", err)
		}
		update := bson.D{
			{"$set", bson.M{"name": "张三三", "age": 18}},
		}
		_, err = collectionStudent.UpdateOne(ctx, filter, update)
		if err != nil {
			fmt.Println("UpdateOne err:", err)
		}

		return nil, nil
	}, txnOptions)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值