How to Create an Index Using the Golang Driver for MongoDB
Introduction
This tutorial will explain how to create a MongoDB index with the Golang driver for MongoDB. Indexes are extremely helpful in speeding up access to MongoDB data by optimizing the data structure. This is accomplished by creating a list of particular fields values to render the data. This article will show how to easily create MongoDB indexes with Golang, how to createone MongoDB index with Golang, createmany MongoDB indexes with Golang and how to use the Golang driver for a MongoDB index.
The structure of the CreateOne API call
Regardless of the language, the method call used to create an index using the most recent driver will be the createIndex()
, createOne()
, create_index()
method, or the Indexes().CreateOne
method in the case of the official Golang driver API.
The method call requires the passing of a key, or the field used to index the data, and an integer for sort order, either a 1
for ascending or -1
for descending order. Options for the second parameter may also be required. Here is an example:
1 | database.coll.createIndex( |CONTEXT|, { |KEY| : |SORT_ORDER|, |OPTIONS| } ) |
The following is the index_view.go
page on the Github repository for the mongo-go-golang
driver structures the CreateOne()
method:
1 2 | // CreateOne creates a single index in the collection specified by the model. func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts, *options.CreateIndexesOptions) (string, error) |
Prerequisites for Creating a MongoDB Index in Golang
MongoDB must be running; type
mongo
to enter the Mongo Shell.Golang must be installed on the same machine running MongoDB with the
$GOPATH
directory for the Golang projects set.The official
mongo-go-driver
Golang driver for MongoDB must be installed on the same machine. Confirm the installation with the following command:
1 | go get go.mongodb.org/mongo-driver/mongo |
- MongoDB database and collections must be on the server running the Golang scripts for the API calls.
How to Setup a MongoDB Environment in a Golang Script
Use the touch
command, or a text editor like Vim or Nano, to create a new Golang script (.go
). Make sure the script is in the system’s $GOPATH
.
How to import the necessary MongoDB and Golang packages.
Use Golang’s import
statement, shown below, to import the Golang and MongoDB packages to create an index:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package main import ( // Built-in Golang packages "context" // manage multiple requests "fmt" // Println() function "os" "reflect" // get an object type "time" // Official 'mongo-go-driver' packages "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx" ) |
How to declare the MongoDB Golang driver’s main() function.
Use the follwing func
command to declare the main()
function where all of the MongoDB API calls will take place:
1 | func main() { |
How to connect to MongoDB in Golang.
Use the options.Client()
instance that will be used in creating a new connection to MongoDB. Make sure to change the host and port URI string, as show below, to match the server’s domain and MongoDB settings:
1 2 3 | // Declare host and port options to pass to the Connect() method clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") fmt.Println("clientOptions type:", reflect.TypeOf(clientOptions), "\n") |
Execute the following command to pass the clientOptions
instance to the mongo.Connect()
method and make sure to pass a context.TODO()
object to it:
1 2 3 4 5 6 | // Connect to the MongoDB and return Client instance client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { fmt.Println("mongo.Connect() ERROR:", err) os.Exit(1) } |
How to Create a Context Object for the MongoDB API Calls
Use the following command with the time
package and create a new context instance that can be used to manage multiple API calls:
1 2 | // Declare Context type object for managing multiple API requests ctx, _ := context.WithTimeout(context.Background(), 15*time.Second) |
How to Declare a New MongoDB Collection Instance from a Database using the Golang Driver
Execute the following command to create a new MongoDB collection instance and make sure to pass the correct collection and database string names to the methods:
1 2 3 | // Access a MongoDB collection through a database col := client.Database("some_database").Collection("Some Collection") fmt.Println("Collection type:", reflect.TypeOf(col), "\n") |
How to Declare an Index Model and Pass it to the Golang Driver’s CreateOne() Method
Use the following command to declare a mongo.IndexModel{}
instance with the index string name and sort operation order (use -1
for descending and 1
for ascending):
1 2 3 4 5 6 7 | // Declare an index model object to pass to CreateOne() // db.members.createIndex( { "SOME_FIELD": 1 }, { unique: true } ) mod := mongo.IndexModel{ Keys: bson.M{ "Some Field": 1, // index in ascending order }, Options: nil, } |
How to pass the IndexModel() instance to the MongoDB CreateOne() method.
Execute the following command to pass the context (ctx
) instance to the Indexes().CreateOne()
method and have it return the index name as a string:
1 2 | // Create an Index using the CreateOne() method ind, err := col.Indexes().CreateOne(ctx, mod) |
How to use the Golang driver to return errors and use fmt.Println() to print the errors to the terminal.
The following is a return errors and print example:
1 2 3 4 5 6 7 8 9 | // Check if the CreateOne() method returned any errors if err != nil { fmt.Println("Indexes().CreateOne() ERROR:", err) os.Exit(1) // exit in case of error } else { // API call returns string of the index name fmt.Println("CreateOne() index:", ind) fmt.Println("CreateOne() type:", reflect.TypeOf(ind), "\n") } |
How to Pass Methods to the CreateOne() method’s Options Parameter
Optionally pass options.Index()
method calls to the IndexModel’s Options
parameter. The following example uses the -1
descending sort order and an integer field for its Keys
:
1 2 3 4 5 6 7 8 | // Declare an index model object to pass to CreateOne() with options mod = mongo.IndexModel{ Keys: bson.M{ "Some Int": -1, // index in descending order }, // create UniqueIndex option Options: options.Index().SetUnique(true), } |
How to Create Multiple MongoDB Indexes Using the CreateIndexes() Method
This section will explain how to create an array of mongo.IndexModel{}
objects using the bsonx
data types ("go.mongodb.org/mongo-driver/x/bsonx"
package) to create multiple indexes.
How to pass bsonx.Doc objects to the mongo.IndexModel() method to create indexes.
The following example shows how to create multiple, complex MongoDB indexes:
1 2 3 4 5 6 7 8 9 | // Declare an array of bsonx models for the indexes models := []mongo.IndexModel{ { Keys: bsonx.Doc{{Key: "Some Field", Value: bsonx.String("text")}}, }, { Keys: bsonx.Doc{{Key: "Some Int", Value: bsonx.Int32(-1)}}, }, } |
Passing the IndexModel array to the CreateIndexes() method to create complex indexes.
The following examples shows how to create another options instance for the CreateIndexes()
method:
1 2 3 4 5 6 7 8 9 10 11 12 | // Declare an options object opts := options.CreateIndexes().SetMaxTime(10 * time.Second) _, err = col.Indexes().CreateMany(ctx, models, opts) // Check for the options errors if err != nil { fmt.Println("Indexes().CreateIndexes() ERROR:", err) os.Exit(1) // exit in case of error } else { fmt.Println("CreateIndexes() opts:", opts) } } |
How to pass the options instance with the models to the Golang driver’s CreateMany() method.
The following example shows how to execute the CreateMany()
method:
1 2 3 4 5 6 7 8 9 10 11 12 | // Declare an options object opts := options.CreateIndexes().SetMaxTime(10 * time.Second) _, err = col.Indexes().CreateMany(ctx, models, opts) // Check for the options errors if err != nil { fmt.Println("Indexes().CreateMany() ERROR:", err) os.Exit(1) // exit in case of error } else { fmt.Println("CreateMany() option:", opts) } } |
Conclusion
This tutorial explained how to create a MongoDB index with the Golang driver for MongoDB. Explanations and examples were provided for setting up a MongoDB environment in a Golang script, using the mongo-go-driver to create an index and how to use Go for a MongoDB index and using the Golang driver for a MongoDB index with the CreateIndexes() method. The tutorial also explained how to use the Golang driver to return errors and print the errors to the terminal and pass the IndexModel array to the CreateIndexes()
method to create complex indexes. Remember that the example in this tutorial used the -1
descending sort order and an integer field for its keys.
How to use the MongoDB Compass UI to verify that the indexes were created.
With MongoDB Compass installed and running, click on the collection used for these API calls, on the left-hand side of the screen, and click on the Indexes tab to verify the indexes were successfully created.
Just the Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | package main import ( // Built-in Golang packages "context" // manage multiple requests "fmt" // Println() function "os" "reflect" // get an object type "time" // Official 'mongo-go-driver' packages "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/bsonx" ) func main() { // Declare host and port options to pass to the Connect() method clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") fmt.Println("clientOptions type:", reflect.TypeOf(clientOptions), "\n") // Connect to the MongoDB and return Client instance client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { fmt.Println("mongo.Connect() ERROR:", err) os.Exit(1) } // Declare Context type object for managing multiple API requests ctx, _ := context.WithTimeout(context.Background(), 15*time.Second) // Access a MongoDB collection through a database col := client.Database("some_database").Collection("Some Collection") fmt.Println("Collection type:", reflect.TypeOf(col), "\n") // Declare an index model object to pass to CreateOne() // db.members.createIndex( { "SOME_FIELD": 1 }, { unique: true } ) mod := mongo.IndexModel{ Keys: bson.M{ "Some Field": 1, // index in ascending order }, Options: nil, } // Create an Index using the CreateOne() method ind, err := col.Indexes().CreateOne(ctx, mod) // Check if the CreateOne() method returned any errors if err != nil { fmt.Println("Indexes().CreateOne() ERROR:", err) os.Exit(1) // exit in case of error } else { // API call returns string of the index name fmt.Println("CreateOne() index:", ind) fmt.Println("CreateOne() type:", reflect.TypeOf(ind), "\n") } // Declare an index model object to pass to CreateOne() with options) mod = mongo.IndexModel{ Keys: bson.M{ "Some Int": -1, // index in descending order }, // create UniqueIndex option Options: options.Index().SetUnique(true), } // Create an Index using the CreateOne() method ind, err = col.Indexes().CreateOne(ctx, mod) // Check if the CreateOne() method returned any errors if err != nil { fmt.Println("Indexes().CreateOne() ERROR:", err) os.Exit(1) // exit in case of error } else { // API call returns string of the index name fmt.Println("CreateOne() index:", ind) fmt.Println("CreateOne() type:", reflect.TypeOf(ind), "\n") } // Declare an array of bsonx models for the indexes models := []mongo.IndexModel{ { Keys: bsonx.Doc{{Key: "Some Field", Value: bsonx.String("text")}}, }, { Keys: bsonx.Doc{{Key: "Some Int", Value: bsonx.Int32(-1)}}, }, } // Declare an options object opts := options.CreateIndexes().SetMaxTime(10 * time.Second) _, err = col.Indexes().CreateMany(ctx, models, opts) // Check for the options errors if err != nil { fmt.Println("Indexes().CreateMany() ERROR:", err) os.Exit(1) // exit in case of error } else { fmt.Println("CreateMany() option:", opts) } } |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started