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?

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

Leave a Reply