How to check if collection exists or not MongoDB Golang

huangapple go评论98阅读模式
英文:

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函数,当我们传递一个集合名称时,它返回一个集合。那么如果没有集合,我该如何检查它是否存在?
我尝试了很多方法,但都失败了。

英文:

I am new to GO language and I am using MongoDB with it. I am creating a backend for an application and its frontend on Angular 4. I want to check if collection exists or not.

Here is my code and I have checked it using nil.

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

I have created a GetCollection function which return a collection when we pass it a collection name.
So when if there is no collection how can I check that if it exists or not?
I have tried many things but failed.

答案1

得分: 8

你可以简单地使用Database.CollectionNames()方法,该方法返回给定数据库中存在的集合名称。它返回一个切片,你需要检查你的集合是否在其中列出。

sess := ... // 获取会话
db := sess.DB("") // 获取数据库,如果连接URL中没有给出数据库名称,则使用数据库名称

names, err := db.CollectionNames()
if err != nil {
    // 处理错误
    log.Printf("获取集合名称失败:%v", err)
    return
}

// 在names切片中进行搜索,例如
for _, name := range names {
    if name == "collectionToCheck" {
        log.Printf("集合存在!")
        break
    }
}

但正如Neil Lunn在他的评论中所写的那样,你不应该需要这样做。你应该改变你的逻辑,使用MongoDB而不是依赖于这个检查。如果你尝试插入一个文档,集合会自动创建,而从不存在的集合查询不会产生错误(当然也没有结果)。

英文:

You may simply use the Database.CollectionNames() method which returns the collection names present in the given db. It returns a slice in which you have to check if your collection is listed.

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

But as Neil Lunn wrote in his comments, you shouldn't need this. You should change your logic to use MongoDB not to rely on this check. Collections are created automatically if you try to insert a document, and querying from non-existing collections yields no error (and no result of course).

huangapple
  • 本文由 发表于 2017年9月19日 14:11:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/46293070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定