如何检查集合是否存在MongoDB Golang [英] How to check if collection exists or not MongoDB Golang

查看:1519
本文介绍了如何检查集合是否存在MongoDB Golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的代码,我已经使用 nil 对其进行了检查.

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

我创建了一个 GetCollection 函数,当我们传递一个集合名称时,该函数将返回一个集合. 因此,如果没有集合,该如何检查它是否存在? 我尝试了很多事情,但是失败了.

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.

推荐答案

您可以简单地使用

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

但是,正如尼尔·伦恩(Neil Lunn)在他的评论中所写,您不需要此.您应该更改逻辑以使用MongoDB而不依赖此检查.如果您尝试插入文档,则会自动创建集合,并且从不存在的集合中查询不会产生错误(当然也不会产生结果).

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).

这篇关于如何检查集合是否存在MongoDB Golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆