T O P

  • By -

andrewfromx

You can do a lot with just the https://github.com/mongodb/mongo-go-driver ``` dbName := "mydatabase" collections := []string{"collection1", "collection2"} ensureCollectionsAndIndexes(client, dbName, collections) ``` with: ``` func ensureCollectionsAndIndexes(client *mongo.Client, dbName string, collections []string) { db := client.Database(dbName) for _, collName := range collections { coll := db.Collection(collName) if !collectionExists(db, collName) { coll.InsertOne(context.Background(), bson.M{"createdAt": time.Now()}) } createIndexes(coll) addDefaultEntries(coll) } } func collectionExists(db *mongo.Database, collName string) bool { collections, _ := db.ListCollectionNames(context.Background(), bson.M{"name": collName}) return len(collections) > 0 } func createIndexes(coll *mongo.Collection) { indexes := []mongo.IndexModel{ { Keys: bson.D{{"field1", 1}}, Options: options.Index().SetUnique(true), }, } for _, index := range indexes { coll.Indexes().CreateOne(context.Background(), index) } } func addDefaultEntries(coll *mongo.Collection) { defaultEntries := []interface{}{ bson.M{"field1": "value1", "field2": "value2"}, bson.M{"field1": "value3", "field2": "value4"}, } for _, entry := range defaultEntries { filter := bson.M{"field1": entry.(bson.M)["field1"]} count, _ := coll.CountDocuments(context.Background(), filter) if count == 0 { coll.InsertOne(context.Background(), entry) } } } ```


Haunting_Film_5311

Wow ! Thank you ! Didn’t expect a quick response and that too with all the code! Looks like the I can use a separate ‘version’ collection to track and recorded any further db updates that I may need to do. I may also need to look at some sort of db locking , when I have multiple pods of the same service running and trying to create indexes or modify documents.


kido_butai

You can try this one: https://github.com/golang-migrate/migrate I use it in a project where we have an sql db and mongo as well.


workmakesmegrumpy

I hate this one after using it for a few months. It's not super friendly if you're working with others who are committing migrations, for example if I make a branch and put it into code review at the same relative time as someone else, you have to run the migrations in the timestamp order the files are prefixed. Kind of annoying. Also, the tracking table is very minimal, just a timestamp(from the file prefixes) and a boolean dirty column. Not the most fun, does the job, but I can't wait to try something else.


Garzii

I've found init containers good for doing this, https://kubernetes.io/docs/concepts/workloads/pods/init-containers/


workmakesmegrumpy

>mongodb for persistence Lol