为了账号安全,请及时绑定邮箱和手机立即绑定

mongodb golang检查集合存在

mongodb golang检查集合存在

Go
森栏 2022-10-24 09:04:49
我需要检查一个集合是否存在。我创建了以下功能: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.Clientvar mongo_cliente *mongo.Databasevar coleccion *mongo.Collectionvar ctx context.Contextvar cancelar context.CancelFunc问题是下一句话:名称,错误:= cliente.CollectionNames()什么类型的数据或如何使用方法 CollectionNames()?有人有示例源代码吗?
查看完整描述

1 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

Database.CollectionNames()返回 db 数据库中存在的集合名称。返回类型是slice这样,您需要检查您的收藏是否已列出。


请查看官方文档:https ://pkg.go.dev/gopkg.in/mgo.v2#Database.CollectionNames


sess := ... // obtain session

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


names, err := db.CollectionNames()

if err != nil {

    // Handle error

    log.Printf("Failed to get coll names: %v", err)

    return

}


// Simply search in the names slice, e.g.

for _, name := range names {

    if name == "collectionToCheck" {

        log.Printf("The collection exists!")

        break

    }

}


查看完整回答
反对 回复 2022-10-24
  • 1 回答
  • 0 关注
  • 202 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号