dezdichado
dezdichado

Reputation: 162

Mongo-go driver version of session.copy()

I am migrating a go backend from using mgo to mongo-go. The service has lots of code and I have completed most of it except for a part that deals with session.Copy() method from the old mgo. The relevant snippet is below:

import (
    "gopkg.in/mgo.v2"
)
...
type Store struct {
    session *mgo.Session
}


func (s *Store) collection(collectionName string) (*mgo.Session, *mgo.Collection) {
    session := s.session.Copy()
    collection := session.DB("").C(collectionName)

    return session, collection
}

I want to rewrite this while respecting the overall design but I am not certain what to do about that line session := s.session.Copy() - I want to do something like:

import(
    "go.mongodb.org/mongo-driver/mongo"
)
type Store struct {
    client *mongo.Client
}


func (s *Store) collection(collectionName string) (*mongo.Client, *mongo.Collection) {
    client, err := s.client."what method to call here"
    if err != nil {
       //error will be handled here
    }
    collection := session.Database(DBName).Collection(collectionName)

    return session, collection
}

My understanding is that the session.Copy() method respects the original connection already in place but only starts a new session based on this as explained in here https://pkg.go.dev/gopkg.in/mgo.v2#Session.Copy . There are several methods that seem like I can use and m.client.StartSession(opts ...*options.SessionOptions) looks like the natural candidate. But it's documentation is confusing me since the connection is already established in the main.go via something like:

clientOptions := options.Client().ApplyURI("URI")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        log.Fatal(err)
    }

Upvotes: 2

Views: 156

Answers (1)

icza
icza

Reputation: 417612

mgo's session and mongo-go's session are 2 different entities.

mgo's session:

Session represents a communication session with the database.

mongo-go's session:

Session is an interface that represents a MongoDB logical session. Sessions can be used to enable causal consistency for a group of operations or to execute operations in an ACID transaction.

mgo's session is a communication session and uses a single underlying connection. mongo-go's session is a logical session, and is not a replacement for mgo's session.

Primary use of mgo's session is to take advantage of multiple underlying connections. mongo-go manages an internal pool and you do not need to create a new session to use multiple connections. This is handled automatically and internally in mongo-go. You do not need to add anything to "replace" mgo's session.Copy(), omit that line.

See related questions:

Concurrency in gopkg.in/mgo.v2 (Mongo, Go)

MongoDB transactions, the callback API approach

Upvotes: 1

Related Questions