The questioner
The questioner

Reputation: 724

Ways to create mongodb index in Golang

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.

Upvotes: 0

Views: 969

Answers (1)

Alish Giri
Alish Giri

Reputation: 2236

I am using go.mongodb.org/mongo-driver v1.12.1 package.

And I did it this way:

func createUsersIndex() {
    indexModals := []mongo.IndexModel{
        {Keys: bson.D{{Key: "display_name", Value: 1}}},
        {Keys: bson.D{{Key: "email", Value: 1}}, Options: options.Index().SetUnique(true)},
        {Keys: bson.D{{Key: "phone_number", Value: 1}}, Options: options.Index().SetUnique(true)},
    }

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    _, err := db.dbName.Collection(constant.UsersCollec).Indexes().CreateMany(ctx, indexModals)
    if err != nil {
        panic(err)
    }
}

Now call createUsersIndex func after you initializ database connection.

Upvotes: 0

Related Questions