Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Golang Collection Struct Usage

Hello World,

I’m currently updating a golang library that’s used in all our micro services that incorporates all the database objects and operations we allow them to use. Within every function that makes a call to the database there is a simple line collection := client.Database("").Collection("") which obviously declares the collection being used. Now, below I have the struct returned by Collection()-

type Collection struct {
	client         *Client
	db             *Database
	name           string
	readConcern    *readconcern.ReadConcern
	writeConcern   *writeconcern.WriteConcern
	readPreference *readpref.ReadPref
	readSelector   description.ServerSelector
	writeSelector  description.ServerSelector
	registry       *bsoncodec.Registry
}

I have not dug into the methods associated with Collection, but am I able to globally define collections so multiple functions can use it or should I keep the code the way it is? Keeping in mind the Collection() function will find the lowest latency node for both reading and writing. Also, if you can, is there any decreased performance due to field writes locking the object?

Thanks,
Samuel

Hi Samuel,

You can define the collection globally. One pattern we see often is to store the mongo.Collection instance in a struct that has helper methods to do database operations. The mongo.Collection type is thread-safe, so multiple functions can use the same instance concurrently. As for performance, there shouldn’t be any impact from the driver code itself as the collection is immutable so there are no locks to modify collection fields when executing an operation.