Updated on 2023-10-08 GMT+08:00

Accessing a Database

Accessing DataBase

If an initialized MongoClient instance exists, 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.

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