Home > Enterprise >  Is mongodb client driver concurrent safe?
Is mongodb client driver concurrent safe?

Time:08-14

In the below code from codebase, mongodb client is created(as shown below):

import (
    "context"
    "time"

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

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

In our scenario:

Goroutine 1 uses collection1 for read & write operations:

  collection1 := client.Database("testing").Collection("collectionone")

Go-routine 2 uses both collection1 &collection2 for read & write operations:

 collection2 := client.Database("testing").Collection("collectiontwo")

Is client concurrent safe to be used in multiple go-routines?

CodePudding user response:

The documentation of mongo.Database explicitly states that:

Database is a handle to a MongoDB database. It is safe for concurrent use by multiple goroutines.

And mongo.Client that:

Client is a handle representing a pool of connections to a MongoDB deployment. It is safe for concurrent use by multiple goroutines.

And mongo.Collection:

Collection is a handle to a MongoDB collection. It is safe for concurrent use by multiple goroutines.

See related: goroutine create multiple mongodb connection

  • Related