0

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?

icza
  • 389,944
  • 63
  • 907
  • 827
overexchange
  • 15,768
  • 30
  • 152
  • 347
  • 1
    Concurrency safety is a problem the database itself has to deal with. What if your code connects and someone else from another application as well? So you really have to ask yourself, is mongodb concurrency safe? – The Fool Aug 13 '22 at 06:00
  • 1
    @TheFool mongodb is concurrent safe. But my question is, is client driver concurrent safe? – overexchange Aug 13 '22 at 06:15

1 Answers1

5

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

icza
  • 389,944
  • 63
  • 907
  • 827