Golang Mongo BulkWrite upsert 用法示例

该示例展示了如何在Go中使用mongo-driver库进行MongoDB的BulkWrite操作,更新两个文档的电子邮件字段,同时设置upsert选项为true。代码创建了一个上下文,连接到MongoDB服务器,定义了两个更新模型并执行了批量写入操作。
摘要由CSDN通过智能技术生成

文档地址: https://godoc.org/go.mongodb.org/mongo-driver/mongo#example-Collection-BulkWrite

package main

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

import mog 	"go.mongodb.org/mongo-driver/mongo"

func main(){
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	host := "填写你的mongodb地址"
	client, err := mog.Connect(ctx, options.Client().ApplyURI(host))
	if err != nil {
		panic(err)
	}

	defer cancel()
	firstUpdate := bson.D{{"$set", bson.D{{"email", "2firstEmail@example.com"}}}}
	secondUpdate := bson.D{{"$set", bson.D{{"email", "2secondEmail@example.com"}}}}
	models := []mog.WriteModel{
		mog.NewUpdateOneModel().SetFilter(bson.D{{"_id", "firstID" }}).SetUpdate(firstUpdate).SetUpsert(true),
		mog.NewUpdateOneModel().SetFilter(bson.D{{"_id", "secondID" }}).SetUpdate(secondUpdate).SetUpsert(true),
	}

	opts := options.BulkWrite().SetOrdered(false)
	res, err := client.Database(conf.Mongo.Database).Collection("test_bulk").BulkWrite(context.TODO(), models, opts)

	if err != nil {
		fmt.Println( err)
	}

	fmt.Println( res )

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值