Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if collection exists or not MongoDB Golang

Tags:

mongodb

go

mgo

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.

like image 570
Habib Avatar asked Sep 19 '17 06:09

Habib


People also ask

What is the command to check existence of collection in MongoDB?

In MongoDB, we can check the existence of the field in the specified collection using the $exists operator.

Does MongoDB Create collection if not exists?

If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.

Where can I find collection name in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().


1 Answers

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

like image 91
icza Avatar answered Oct 19 '22 00:10

icza