文档地址: 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 )
}