Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the MongoDB Go Driver, how do I set up connection pooling?

I'm using the MongoDB Go Driver in my Go (1.11) server which runs on Google Cloud's App Engine. I'm not really sure if I still manually have to set up connection pooling or if it's already being taken care of out of the box. For example I'm not entirely sure what the context (with timeout) exactly means.

My code looks like this:

package tools

import (
    "context"
    "time"
    "valuation-app/settings"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// ConnectToDB starts a new database connection and returns a reference to it
func ConnectToDB() (*mongo.Database, error) {
    settings := settings.Get().Database
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    options := options.Client().ApplyURI(settings.URI)
    options.SetMaxPoolSize(10)
    client, err := mongo.Connect(ctx, options)
    if err != nil {
        return nil, err
    }

    return client.Database(settings.DatabaseName), nil
}
like image 483
Prutser Avatar asked Jun 21 '19 13:06

Prutser


People also ask

Does MongoDB use connection pooling?

Sharded Cluster Connection Poolingmongos routers have connection pools for each node in the cluster. The availability of connections to individual nodes within a sharded cluster affects latency. Operations must wait for a connection to be established.

What is the default connection pool size in MongoDB?

100 ( maxPoolSize default 100 ) x 4 (application servers) = 400 (incoming connections to each mongod).

Can I use MongoDB with go?

Go is one of the newest languages to get an official MongoDB driver, and the combination of Go's compiled performance and lightweight, data-friendly syntax makes Go with MongoDB a fantastic match for building data-driven applications.


1 Answers

From comments:

Mongo-go-driver takes care of connection pooling by default(100 connection by default)

You can read the source code here

like image 80
Amin Shojaei Avatar answered Sep 23 '22 11:09

Amin Shojaei