I'm building a Go application deployed on Kubernetes that uses MongoDB as the database. Currently, my application includes logic to create indexes on collections during every pod startup. While this ensures that indexes are always up-to-date, it adds overhead to the startup process and seems redundant since indexes typically don't change frequently.
My question is:
- What are the best practices for managing MongoDB indexes in such a setup to avoid executing index creation
logicon every pod startup? - Are there any recommended patterns or tools to ensure indexes are created/updated when necessary without impacting application startup times?
Currently, I have the following function in my repository to initialize indexes for a MongoDB collection:
func (p *ForbiddenD) initIndexes(ctx context.Context) {
indexes := []mongo.IndexModel{
{
Keys: bson.M{"passengerId": 1},
Options: options.Index().SetUnique(true),
},
}
_, err := p.collection.Indexes().CreateMany(ctx, indexes)
if err != nil {
return
}
}
This function runs on every application startup, which ensures that indexes exist but feels redundant and inefficient since indexes don't change often.
My goal is to avoid executing this function every time the application starts and implement a mechanism similar to migrations in SQL-based databases to manage indexes in MongoDB.
My setup:
- Go application using the MongoDB Go driver.
- Deployed on Kubernetes, with multiple replicas.
What are the best practices for handling MongoDB index creation in this scenario? Is there a way to check and apply index updates only when necessary, similar to database migrations?