@@ -74,3 +74,36 @@ func CreateCollections(ctx context.Context, dbName string, collectionName string
7474 log .Printf ("✅ Collection already present: %s" , collectionName )
7575 }
7676}
77+
78+ func CreateIndex (dbName string , collectionName string , indexModel mongo.IndexModel ) {
79+ ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
80+ defer cancel ()
81+
82+ _ , err := GetDb (dbName ).Collection (collectionName ).Indexes ().CreateOne (ctx , indexModel )
83+
84+ if err != nil {
85+ log .Fatalf ("❌ Failed to create index for collection: %s in db: %s" , collectionName , dbName )
86+ log .Fatalf ("❌ Error while creating creating index: %v" , err )
87+ } else {
88+ log .Println ("✅ Index Created Successfully" )
89+ }
90+ }
91+
92+ func CreateUniqueIndex (dbName string , collectionName string , field string ) {
93+ indexModel := mongo.IndexModel {
94+ Keys : bson.M {field : 1 },
95+ Options : options .Index ().SetUnique (true ),
96+ }
97+
98+ ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
99+ defer cancel ()
100+
101+ _ , err := GetDb (dbName ).Collection (collectionName ).Indexes ().CreateOne (ctx , indexModel )
102+
103+ if err != nil {
104+ log .Fatalf ("❌ Failed to create index for collection: %s in db: %s" , collectionName , dbName )
105+ log .Fatalf ("❌ Error while creating creating index: %v" , err )
106+ } else {
107+ log .Println ("✅ Index Created Successfully" )
108+ }
109+ }
0 commit comments