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.
In MongoDB, we can check the existence of the field in the specified collection using the $exists operator.
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.
To list all collections in Mongo shell, you can use the function getCollectionNames().
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With