I am having trouble figuring out how to programmatically create collections using the Golang driver. I can see that the Java driver has the API to create collections, but the Golang driver either doesn’t have such API, or it is buried somewhere I can’t find. Any help is appreciated.
Hi @Pranay_Singhal,
You can use Database.RunCommand to execute a command. For example:
db := client.Database("dbName")
command := bson.D{{"create", "collectionName"}}
var result bson.M
if err := db.RunCommand(context.TODO(), command).Decode(&result); err != nil {
log.Fatal(err)
}
See also MongoDB create command for more information.
Regards,
Wan.
Thanks @wan, this worked for me, and will solve my purpose.
1 Like
func openCollection(dbClient *mongo.Client, collectionName string) *mongo.Collection {
var collection *mongo.Collection = dbClient.Database(“DatabaseName”).Collection(collectionName)
return collection
}