I currently create an index by:
In package db:
// CreateUniqueIndex create UniqueIndex
func CreateUniqueIndex(collection string, keys ...string) {
keysDoc := bsonx.Doc{}
for _, key := range keys {
if strings.HasPrefix(key, "-") {
keysDoc = keysDoc.Append(strings.TrimLeft(key, "-"), bsonx.Int32(-1))
} else {
keysDoc = keysDoc.Append(key, bsonx.Int32(1))
}
}
idxRet, err := database.Collection(collection).Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: keysDoc,
Options: options.Index().SetUnique(true),
},
options.CreateIndexes().SetMaxTime(10*time.Second),
)
if err != nil {
log.Fatal(err)
}
log.Println("collection.Indexes().CreateOne:", idxRet)
}
And in the main.go file:
db.CreateUniqueIndex("User", "email")
My concern is that the index will be created when I start the server. However, what if a user creates an account and will his email be index?
So, please advise the correct way to handle mongodb index.