我需要使用CollectionNames()方法來列出資料庫的所有集合。
我將不得不在 mongoDB 中創建一個會話:
sess := ... // obtain session
db := sess.DB("") // Get db, use db name if not given in connection url
names, err := db.CollectionNames()
我在哪里可以找到在 MongoDB 中獲取會話的示例?
我一直連接到下一個方式的DB:
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)
如何創建會話?
提前致謝!!
uj5u.com熱心網友回復:
您似乎混淆/混合了不同的 MongoDB 驅動程式。在DB.CollectionNames()中存在mgo哪些是舊的,沒有維護的驅動程式。
您使用的驅動程式是官方mongo-go驅動程式,它具有不同的獲取現有集合串列的方法。
該mongo-go驅動程式有Database.ListCollectionNames()方法,你可以使用這樣的:
names, err := mongo_cliente.ListCollectionNames(ctx, bson.D{})
// names is a []string holding all the existing collection names
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/395698.html
