@@ -28,9 +28,60 @@ func main() {
2828 Password: " your_mongodb_password" ,
2929 Host: " localhost" ,
3030 Port: " your_mongodb_port" ,
31- DbName: " your_db_name" ,
3231 }
3332
3433 mongodb_client.ConnectDb (&mongodbConfig)
3534}
36- ```
35+ ```
36+
37+ ### Get database by name
38+
39+ ``` go
40+ func GetDb () {
41+ // this function returns *mongo.Database
42+ database := mongodb_client.GetDb (" your_database_name" )
43+ }
44+ ```
45+
46+ ### Create collections
47+
48+ ``` go
49+ // Create Collections
50+ func CreateCollections (config *config .Config ) {
51+ bgCtx := context.Background ()
52+ ctx , cancel := context.WithTimeout (bgCtx, 5 *time.Second )
53+ defer cancel ()
54+
55+ collections := []string {
56+ // list of your collections which you want to create under a database
57+ }
58+
59+ // List existing collections
60+ existingCollections , err := mongodb_client.GetDb ().ListCollectionNames (ctx, bson.D {})
61+ log.Printf (" ✅ List of Collections: %s " , existingCollections)
62+
63+ if err != nil {
64+ log.Fatalf (" ❌ Failed to list collections in DB %s : %v " , config.ClientDbName , err)
65+ }
66+
67+ existingMap := make (map [string ]bool )
68+
69+ for _ , name := range existingCollections {
70+ existingMap[name] = true
71+ }
72+
73+ log.Printf (" ✅ Collections already present: %v " , existingMap)
74+
75+ // Create only missing collections
76+ for _ , collection := range collections {
77+ if !existingMap[collection] {
78+ if err := mongodb_client.GetDb (" your_database_name" ).CreateCollection (ctx, collection); err != nil {
79+ log.Fatalf (" ❌ Failed to create collection %s : %v " , collection, err)
80+ }
81+
82+ log.Printf (" ✅ Created collection: %s " , collection)
83+ }
84+ }
85+ }
86+
87+ ```
0 commit comments