Skip to content

Commit 1450678

Browse files
author
Amit
committed
updated readme.md and updated function to support multi database
1 parent ea10fd8 commit 1450678

File tree

3 files changed

+55
-4
lines changed

3 files changed

+55
-4
lines changed

Readme.md

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
```

mongodb_client/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package mongodb_client
22

3-
type MongodbConfigV2 struct {
3+
type MongodbConfig struct {
44
Username string
55
Password string
66
Host string

mongodb_client/mongodb-client.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func GetDb(dbName string) *mongo.Database {
2424
}
2525

2626
// Connect Mongodb function will initialize and connect to mongodb based on the URL, Port and Host passed via config
27-
func ConnectDb(config *MongodbConfigV2) {
27+
func ConnectDb(config *MongodbConfig) {
2828
// Get MongoDB URI from environment variable if set, otherwise use default
2929
mongoDbUrl := fmt.Sprintf("mongodb://%s:%s@%s:%s", config.Username, config.Password, config.Host, config.Port)
3030

0 commit comments

Comments
 (0)