Created
February 4, 2026 18:41
-
-
Save mmcclimon/91758c704134f8b454548ddec19b1203 to your computer and use it in GitHub Desktop.
v1 vs v2 driver behavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "fmt" | |
| "log" | |
| "time" | |
| bson1 "go.mongodb.org/mongo-driver/bson" | |
| mongo1 "go.mongodb.org/mongo-driver/mongo" | |
| options1 "go.mongodb.org/mongo-driver/mongo/options" | |
| writeconcern1 "go.mongodb.org/mongo-driver/mongo/writeconcern" | |
| "go.mongodb.org/mongo-driver/v2/bson" | |
| "go.mongodb.org/mongo-driver/v2/mongo" | |
| "go.mongodb.org/mongo-driver/v2/mongo/options" | |
| "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" | |
| "go.mongodb.org/mongo-driver/v2/x/mongo/driver/xoptions" | |
| ) | |
| func main() { | |
| ctx := context.Background() | |
| ports := []int{33333, 33334, 33335} | |
| doV1(ctx, ports) | |
| fmt.Println("---") | |
| doV2(ctx, ports) | |
| } | |
| func doV1(ctx context.Context, ports []int) { | |
| True := true | |
| for _, port := range ports { | |
| cs := fmt.Sprintf("mongodb://127.0.0.1:%d/", port) | |
| opts := options1.Client(). | |
| ApplyURI(cs). | |
| SetDirect(true). | |
| SetConnectTimeout(3 * time.Second). | |
| SetWriteConcern(writeconcern1.Majority()) | |
| opts.AuthenticateToAnything = &True | |
| // This is what we did in for v1. | |
| opts.SetSocketTimeout(0) | |
| client, err := mongo1.Connect(ctx, opts) | |
| if err != nil { | |
| log.Fatalf("couldn't connect to mongod on port %d", port) | |
| } | |
| _, err = client.Database("test").Collection("foo").InsertOne(ctx, bson1.D{}) | |
| word := "success" | |
| if err != nil { | |
| word = "fail: " + err.Error() | |
| } | |
| fmt.Printf("v1 port %d: %s\n", port, word) | |
| } | |
| } | |
| func doV2(ctx context.Context, ports []int) { | |
| for _, port := range ports { | |
| cs := fmt.Sprintf("mongodb://127.0.0.1:%d", port) | |
| opts := options.Client(). | |
| ApplyURI(cs). | |
| SetDirect(true). | |
| SetConnectTimeout(3 * time.Second). | |
| SetWriteConcern(writeconcern.Majority()) | |
| _ = xoptions.SetInternalClientOptions(opts, "authenticateToAnything", true) | |
| // And this is a naive translation to v2. | |
| opts.SetTimeout(0) | |
| client, err := mongo.Connect(opts) | |
| if err != nil { | |
| log.Fatalf("couldn't connect to mongod on port %d", port) | |
| } | |
| _, err = client.Database("test").Collection("foo").InsertOne(ctx, bson.D{}) | |
| word := "success" | |
| if err != nil { | |
| word = "fail: " + err.Error() | |
| } | |
| fmt.Printf("v2 port %d: %s\n", port, word) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment