Updated on 2023-09-27 GMT+08:00

Accessing a Database

Accessing a Database

If there is an initialized MongoClient instance, run the following command to access a database:

db:= client.Database("test")

Assessing a Collection

After obtaining a MongoDatabase instance, run the following command to obtain a collection:

coll := db.Collection("testCollection")

Creating a Collection

You can use the CreateCollection() method to create a collection and specify the attributes of the collection during its creation.

db:= client.Database("test") 
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) 
defer cancel() 
sizeInBytes := int64(200000) 
testCollection := db.CreateCollection(ctx,"testCollection",&options.CreateCollectionOptions{SizeInBytes: &sizeInBytes})