我需要检查一个集合是否存在。
我创建了以下功能:
func ExitsCollection(name string) bool {
var exists bool = false
names, err := cliente.CollectionNames()
if err != nil {
log.Println("[-]I cannot retrieve the list of collections")
}
// Simply search in the names
for _, name := range names {
if name == name {
log.Printf("[+]The collection already exists!")
exists = true
break
}
}
if !exists {
log.Println("[+] The collection does not exist")
}
return exists
}
为了连接,我使用下一个功能:
func ConectaBD() {
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)
log.Println("[+]Connected to MongoDB Atlas")
}
我使用以下变量:
var cliente_local *mongo.Client
var mongo_cliente *mongo.Database
var coleccion *mongo.Collection
var ctx context.Context
var cancelar context.CancelFunc
问题是下一句话:
名称,错误:= cliente.CollectionNames()
什么类型的数据或如何使用方法 CollectionNames()?
有人有示例源代码吗?
慕盖茨4494581
相关分类