MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

What happens behind Connect, Database, Collection in the Go driver?

Hello, I understant connect will build a connection with database, return the connection to client, so the “client” here is similar to the concept “session” in globalsign/mgo, right? but what happens in client.Database(“db_name”), I know it will return a reference of the database, such reference is thread safe to use? what happens in db.Collection(“coll_name”)? the reference of collection returned is thread safe too?

Hi @Zhihong_GUO,

so the “client” here is similar to the concept “session” in globalsign/mgo, right?

Although there are similarities between them, they are not quite the same. For example, there is no methods such as session.Copy() or session.Clone(). With mongo-go-driver, you just dial one client which can be passed around between routines (each running whatever commands it needed), and the connection pooling is handled for you.

Also, worth mentioning that there’s also Session in mongo-go-driver, which is an interface that represents a MongoDB logical session.

I know it will return a reference of the database, such reference is thread safe to use? what happens in db.Collection(“coll_name”)?

Client, Database and Collection are safe for concurrent use by multiple goroutines.

Regards,
Wan.

Thank you Wan. So I can do something like that:

type MyService struct {
coll *mongo.Collection //I will save the collect as a member
}

//PaginateDocs can be accessed by several “client” apps
func (serv *MyService) PaginateDocs (id int, filter Filter, opt FindOptions, result interface{}) error {
c, err := serv.coll.Find(context.TODO(), filter, opt) //so here I can use the member, without concern of thread safe
err = c.All(context.TODO(), &result)
return err
}

Thank you for your answer.

Yes, you can pass mongo.Collection around in the application.

Regards,
Wan.

Thanks a lot for the answer!