Dynamic collection creation with unique indexes

I have modified the indexCollection function to the below, to use a name. It still fails with the following error:

➜   go build && ./mongo_test
2020/03/03 13:14:56 indexed the collection 1 time(s).
2020/03/03 13:14:56 failed to index DB: (IndexKeySpecsConflict) Index must have unique name.The existing index: { v: 2, unique: true, key: { param1: 1, param2: 1, param3: 1 }, name: "3params", ns: "brand-new-db.brand-new-collection" } has the same name as the requested index: { v: 2, unique: true, key: { param3: 1, param1: 1, param2: 1 }, name: "3params", ns: "brand-new-db.brand-new-collection" }

I think the problem is that I’m not using an ordered mongo.D (document) type. I’ll run one more test and report back.

func indexCollection(coll *mongo.Collection) error {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	_, err := coll.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys: map[string]int{
			"param1": 1,
			"param2": 1,
			"param3": 1,
		},
		Options: options.Index().SetName("3params").SetUnique(true),
	})
	return err
}
1 Like