func DatabaseConnect() (db *mongo.Database, err error) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
return
}
db = client.Database("students")
return
}
this above function connects to a database which is already present on mongoDB server. But can we write a function silimar to this one, which will create/drop a database and some collections also.
func HandleDatabases(){
// for deleting / creating / managing mongoDB databases and collections ?
}
Using MongoDB, databases and collections do not need to exist prior to using them.
You can run queries against non-existing databases and collections, which will not result in an error, but obviously won't return any documents. When inserting documents into a non-existing database and/or collection, the database and/or collection will be created automatically.
To drop a database, simply use the Database.Drop()
method. To drop a collection, simply use the Collection.Drop()
method.
You only need to create a collection before using it if you want it to create with non-default, special properties. For that, you may use Database.CreateCollection()
.
To find out which databases exist already on the server, you may use the Client.ListDatabases()
or Client.ListDatabaseNames()
methods.
To find out which collections exist already in a database, you may use the Database.ListCollections()
or Database.ListCollectionNames()
methods.