How to check if collection exists or not MongoDB G

2020-02-28 19:31发布

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.

标签: mongodb go mgo
1条回答
beautiful°
2楼-- · 2020-02-28 20:02

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

查看更多
登录 后发表回答