I use this code to get the client for mongodb:
package connectors
import (
"context"
"log"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func GetMongoDBConnection() *mongo.Client {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGODB_URI")))
if err != nil {
log.Fatal(err)
}
return client
}
And im using it like this, to get the connection and insert one document into the db:
dbClient := connectors.GetMongoDBConnection()
coll := dbClient.Database("test").Collection("test")
coll.InsertOne(context.TODO(), bson.M{"key": "value"})
I tried to measure the time by doing:
ConnectionTime := time.Now()
dbClient := connectors.GetMongoDBConnection()
fmt.Println(time.Since(ConnectionTime).Milliseconds())
CollSelectionTime := time.Now()
coll := dbClient.Database("test").Collection("test")
fmt.Println(time.Since(CollSelectionTime).Milliseconds())
InsetionTime := time.Now()
coll.InsertOne(context.TODO(), bson.M{"type": "congelada", "type2": "Masalado"})
fmt.Println(time.Since(InsetionTime).Milliseconds())
The console prints:
0
0
629
So that 629 milliseconds are from the "InsertOne"... But I don't understand why because I tried to insert 10,000 documents and it took like 2000 milliseconds, so I actually don't undestand where that ~600 milliseconds came from...
How can I reduce that time...
CodePudding user response:
Connection, DB selection, or collection selection simply capture the arguments but do not perform any actual operation. Those are used when you make the actual database operation. Thus, the first call to InsertOne
will connect if not already connected, and perform the operation.
After connecting, call Ping
, and that will actually connect to the DB.