How to check if a collection exists or not MongoDB Golang

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

Here is my code, and I tested it using nil .

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

I created a GetCollection function that returns a collection when we pass it the name of the collection. So, if there is no collection, how can I check it if it exists or not? I tried many things but could not.

+5
source share
1 answer

You can simply use the Database.CollectionNames() method, which returns the collection names present in this db. It returns a snippet in which you should check if your collection is included.

 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, eg for _, name := range names { if name == "collectionToCheck" { log.Printf("The collection exists!") break } } 

But, as Neil Lunn wrote in his comments, you don’t need it. You must change your logic to use MongoDB so as not to rely on this check. Collections are created automatically if you try to insert a document, and queries from non-existent collections give no errors (and, of course, are not the result).

+3
source

Source: https://habr.com/ru/post/1271919/


All Articles