如何检查集合是否存在 MongoDB Golang

How to check if collection exists or not MongoDB Golang

我是 GO 语言的新手,我正在使用 MongoDB。我正在为 Angular 4 上的应用程序及其前端创建后端。我想检查集合是否存在。

这是我的代码,我已经使用 nil 检查了它。

collection := GetCollection("users")    
fmt.Println("collection", collection)   
if collection == nil {      
   fmt.Println("Collection is empty")   
}

我创建了一个 GetCollection 函数,当我们向它传递一个集合名称时,它 return 一个集合。 那么,如果没有集合,我该如何检查它是否存在? 我尝试了很多东西但都失败了。

您可以简单地使用 Database.CollectionNames() 方法,该方法 returns collection 名称出现在给定的数据库中。它 returns 一个切片,您必须在其中检查您的 collection 是否已列出。

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
    }
}

但正如 Neil Lunn 在他的评论中所写,你不应该需要这个。您应该更改您的逻辑以使用 MongoDB 不依赖此检查。如果您尝试插入文档,Collections 会自动创建,并且从 non-existing collection 查询不会产生任何错误(当然也不会产生任何结果)。