Skip to content

Commit 4cfc0b3

Browse files
author
Amit
committed
Added create collections function and renamed existing create collections function to create collection.
1 parent 82159a8 commit 4cfc0b3

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

mongodb_client/mongodb-client.go

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ func GetDb(dbName string) *mongo.Database {
2525

2626
// Connect Mongodb function will initialize and connect to mongodb based on the URL, Port and Host passed via config
2727
func ConnectDb(config *MongodbConfig) {
28+
log.Printf("✅ Connecting to MongoDB on port: %s...", config.Port)
29+
2830
// Get MongoDB URI from environment variable if set, otherwise use default
2931
mongoDbUrl := fmt.Sprintf("mongodb://%s:%s@%s:%s", config.Username, config.Password, config.Host, config.Port)
3032

@@ -47,8 +49,8 @@ func ConnectDb(config *MongodbConfig) {
4749
log.Printf("✅ Connected to MongoDB on port: %s", config.Port)
4850
}
4951

50-
// Create Collections
51-
func CreateCollections(dbName string, collectionName string) {
52+
// Create Collection
53+
func CreateCollection(dbName string, collectionName string) {
5254
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
5355
defer cancel()
5456

@@ -78,6 +80,41 @@ func CreateCollections(dbName string, collectionName string) {
7880
}
7981
}
8082

83+
// Create Collections
84+
func CreateCollections(dbName string, collections []string) {
85+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
86+
defer cancel()
87+
88+
db := GetDb(dbName)
89+
90+
// List existing collections
91+
existingCollections, err := db.ListCollectionNames(ctx, bson.D{})
92+
log.Printf("List of Collections: %s", existingCollections)
93+
94+
if err != nil {
95+
log.Fatalf("Failed to list collections in DB %s: %v", dbName, err)
96+
}
97+
98+
existingMap := make(map[string]bool)
99+
100+
for _, name := range existingCollections {
101+
existingMap[name] = true
102+
}
103+
104+
log.Printf("Collections already present: %v", existingMap)
105+
106+
// Create only missing collections
107+
for _, collection := range collections {
108+
if !existingMap[collection] {
109+
if err := db.CreateCollection(ctx, collection); err != nil {
110+
log.Fatalf("Failed to create collection %s: %v", collection, err)
111+
}
112+
113+
log.Printf("Created collection: %s", collection)
114+
}
115+
}
116+
}
117+
81118
func CreateIndex(dbName string, collectionName string, indexModel mongo.IndexModel) {
82119
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
83120
defer cancel()

0 commit comments

Comments
 (0)