Search code examples
mongodbgomongo-go

MongoDB connection pool in Golang official driver


I have two go files in project

  1. main.go

This files creates http server and mongoDB connection and a method which will allow to reuse the connection using following

func ConnectMongoDB() {

    ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)

    // user Connection database

    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb+srv://localhost:27017/demo")

    // Connect to MongoDB
    userclient, err = mongo.Connect(ctx, clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    // Check the connection
    err = userclient.Ping(ctx, nil)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Connected to user MongoDB!")

}

//GetMongoDBClient , return mongo client for CRUD operations
func GetMongoDBClient() *mongo.Client {

    return userclient
}

  1. query.go

This file then define database and then fire query on it

client := GetMongoDBClient()

collection := client.Database("demo").Collection("user")

err := collection.FindOne(context.TODO(), filter).Decode(&user)

When I fired 200 requests , i got email from Atlas saying that i have exceeded my 80 connection limit quota. How to make use of connection pooling here?


Solution

  • Have you tried the MaxPoolSize option:

    clientOptions = clientOptions.SetMaxPoolSize(50)
    

    I haven't tried this in the official mongo driver, but the mgo driver has a similar option that works as expected.