My go code is making a connection to MongoDB like this:
uri := "mongodb://localhost:27017"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyUIR(uri))
if err != nil {
panic(err)
}
I want to create a couple of goroutines that regularly queries the database, and not sure if making every goroutine uses client is safe. What would be the most conventional way to make multiple goroutines interact with the same database?
Single client instance is safe to use in multiple goroutines. From the docs:
Client is a handle representing a pool of connections to a MongoDB deployment. It is safe for concurrent use by multiple goroutines.