1

The go-mongo-driver documentation at https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial recommends the following:

It is best practice to keep a client that is connected to MongoDB around so that the application can make use of connection pooling - you don't want to open and close a connection for each query.

My question is: Is there a best practice for how to do this?

I'm running an RPC service and continually listening for requests. When I receive a request I make a call to the mongo server. What I do not want to do is continually connect and disconnect to mongo.

I've attempted a solution by creating the mongo client as a global variable and then deferring the disconnection in the main function... It does not feel like a good solution.

var mongoClient *mongo.Client = buildMongoClient()

func main() {
  defer disconnectFromMongo()
  *** Do all the things *** 
  ...
}
1
  • You can return a handler from a closure for example. Commented Jul 27, 2019 at 14:51

1 Answer 1

1

For mongo-go-driver, global scope variable for mongo client is the way to go. Behind the scene, that client maintains a pool of tcp connections (exposed via MaxPoolSize, default to 100) and handle connectivity for you, you don't really have control of this abstraction anyway.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.