Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how i get a session in mongodb with golang

I need to use the method CollectionNames() in order to list all the collections of a database.

I will have to create a session in mongoDB:

sess := ... // obtain session
db := sess.DB("") // Get db, use db name if not given in connection url

names, err := db.CollectionNames()

Where could I find a example to get a session in MongoDB?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have always connected with the DB of the next way:

cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))
    if err != nil {
        log.Fatal(err)
    }

    ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
    err = cliente_local.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer cancelar()

    mongo_cliente = cliente_local.Database(DATABASE)

How could I create a session?

Thanks in advance!!

>Solution :

You seem to be confused / mixing different MongoDB drivers. The DB.CollectionNames() exists in the mgo driver which is old and unmaintained.

The driver you use is the official mongo-go driver, which has a different method for obtaining the list of existing collections.

The mongo-go driver has the Database.ListCollectionNames() method, you may use it like this:

names, err := mongo_cliente.ListCollectionNames(ctx, bson.D{})
// names is a []string holding all the existing collection names
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading