Sarthak Jha
Sarthak Jha

Reputation: 43

How to create compound indexes in mongoDB using golang mongo-driver?

I am trying to create an index in the database, but, CreateMany creates indexes on individual columns on the array of columns specified.

But I require a compound index for a couple of columns

Upvotes: 2

Views: 2379

Answers (1)

icza
icza

Reputation: 418435

You specify an index with a value of mongo.IndexModel:

type IndexModel struct {
    // A document describing which keys should be used for the index. It cannot be nil. This must be an order-preserving
    // type such as bson.D. Map types such as bson.M are not valid. See https://docs.mongodb.com/manual/indexes/#indexes
    // for examples of valid documents.
    Keys interface{}

    // The options to use to create the index.
    Options *options.IndexOptions
}

The indexable property (or properties) are given in the Keys field. It does not necessary have to contain a single property. As its name (Keys) and doc hits: it may contain multiple properties, and since order matters, it should be listed with a data structure that preservers order, such as bson.D.

Here's an example creating 2 compound indices, first one using prop1, prop2 and prop3, the second one using prop4 and prop4.

ctx := context.Background()
c := db.Collection("collname")

_, err = c.Indexes().CreateMany(ctx, []mongo.IndexModel{
    // prop1, prop2, prop3
    {
        Keys: bson.D{
            {Key: "prop1", Value: 1}, // prop1 asc
            {Key: "prop2", Value: 1}, // prop2 asc
            {Key: "prop3", Value: -1}, // prop3 desc
        },
    },
    // prop4, prop5
    {
        Keys: bson.D{
            {Key: "prop4", Value: 1}, // prop4 asc
            {Key: "prop5", Value: 1}, // prop5 asc
        },
    },
})
if err != nil {
    log.Printf("Failed to create indices: %v", err)
}

Upvotes: 3

Related Questions