11

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.

Habib
  • 846
  • 2
  • 9
  • 24
  • 1
    The real question is "why should it matter to you?". Is there some specific reason why you think you need to determine whether a collection exists or not? – Neil Lunn Sep 19 '17 at 06:14
  • Yes its really matter for me. I am creating **seeds** in a **users** collection. If there is no **user** and no **collection** than my server will create a collection first than it will create a default user. – Habib Sep 19 '17 at 06:17
  • 3
    You do realize that if you simply ask for the `count` from a collection, then whether it exists or not it always returns a number. So empty or not present would be `0`. There is a distinction, and there are cases where you might actually need to test for the presence of a collection. But your case does not appear to be one of them. – Neil Lunn Sep 19 '17 at 06:24

1 Answers1

8

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

RickyA
  • 15,465
  • 5
  • 71
  • 95
icza
  • 389,944
  • 63
  • 907
  • 827
  • So you mean to say it doesn't matter if a collection exists or not. I just have to add a document? right? – Habib Sep 19 '17 at 07:30
  • 4
    @HabibM.Farooq Exactly. If you attempt to insert a document into a non-existing collection, the collection will be created automatically for you. – icza Sep 19 '17 at 07:37
  • Thank you for your perfect answer and thank you for your help. – Habib Sep 19 '17 at 08:58
  • I want to create a config file in MongoDB Atlas. In the first execution I need to create a collection, but if it is the second execution then this collection has already been created – grafeno30 Dec 27 '21 at 18:34
  • In the code: sess := ... // obtain session db := sess.DB("") // Get db, use db name if not given in connection url. How i get a session: cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))?. – grafeno30 Dec 27 '21 at 18:35
  • @grafeno30 Your question is unclear. It has no significance if a collection exists in MongoDB unless you want to create it with special (non-default) options. You can query a non-existing collection (which results in no documents), and you can insert documents into it (in which case it will be auto-created). You should post a new question if this doesn't answer your question. – icza Dec 27 '21 at 18:55
  • Collections are not created automatically when you use `renameCollection`. All such operations must be guarded by collection existence check. – Alexander Tumin May 23 '22 at 06:40