我是GO语言的新手,我正在使用MongoDB.我正在创建一个应用程序的后端及其在Angular 4上的前端.我想检查是否存在集合.
这是我的代码,我用nil检查了它.
collection := GetCollection("users")
fmt.Println("collection", collection)
if collection == nil {
fmt.Println("Collection is empty")
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个GetCollection函数,当我们传递一个集合名称时,它会返回一个集合.因此,如果没有收集,我如何检查它是否存在?我尝试过很多东西但都失败了.
您可以简单地使用Database.CollectionNames()返回给定db中存在的集合名称的方法.它返回一个切片,您必须在其中检查是否列出了您的集合.
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
}
}
Run Code Online (Sandbox Code Playgroud)
但正如Neil Lunn在评论中写道的那样,你不应该这样做.您应该更改逻辑以使用MongoDB不依赖此检查.如果您尝试插入文档,则会自动创建集合,并且从不存在的集合中查询不会产生错误(当然也没有结果).
| 归档时间: |
|
| 查看次数: |
2359 次 |
| 最近记录: |