Created
February 2, 2025 10:10
-
-
Save ashaffah/f3c30de0338ec2e4c0a842c66447c335 to your computer and use it in GitHub Desktop.
Golang Mongodb dynamic auto indexing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package helpers | |
import ( | |
"context" | |
"log" | |
"time" | |
"go.mongodb.org/mongo-driver/bson" | |
"go.mongodb.org/mongo-driver/mongo" | |
"go.mongodb.org/mongo-driver/mongo/options" | |
) | |
func AutoIndexingCollection[T any](db *mongo.Database, key []string, collectionName string) error { | |
collection := db.Collection(collectionName) | |
var indexModels []mongo.IndexModel | |
for _, k := range key { | |
indexModel := mongo.IndexModel{ | |
Keys: bson.D{{Key: k, Value: 1}}, | |
Options: options.Index().SetUnique(true), | |
} | |
indexModels = append(indexModels, indexModel) | |
} | |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
defer cancel() | |
_, err := collection.Indexes().CreateMany(ctx, indexModels) | |
if err != nil { | |
log.Printf("Error creating index on %v: %v\n", key, err) | |
return err | |
} | |
log.Printf("Successfully created unique index on %s for collection %s\n", key, collectionName) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment