Sobes.tech
Junior — Middle

Have you had experience using indexing in MongoDB to optimize queries?

sobes.tech AI

Answer from AI

Yes, in Go projects, MongoDB is often used with indexes to optimize queries. Indexes in MongoDB significantly speed up data search and filtering, especially on large collections.

In Go, the official driver mongo-go-driver is typically used to work with MongoDB. To utilize indexing, an index is first created on the necessary field, and then queries that use this index are performed.

Example of creating an index in Go:

import (
    "context"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "log"
)

func createIndex(collection *mongo.Collection) {
    indexModel := mongo.IndexModel{
        Keys: bson.D{{Key: "fieldName", Value: 1}}, // 1 for ascending order
        Options: options.Index().SetUnique(false),
    }
    indexName, err := collection.Indexes().CreateOne(context.Background(), indexModel)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Created index:", indexName)
}

After creating the index, queries filtering by fieldName will execute faster.

Using indexes involves understanding which fields to index to improve performance and monitoring index usage with MongoDB profiler.

Have you had experience using indexing in MongoDB to… - sobes.tech