I am writing a golang web service with mongo database, I am using go.mongodb.org/mongo-driver v1.11.6 , a simple query takes more than 2 seconds to complete. The database only has a few records, just for testing, no more than 10 records.
I was looking for the part of the code that was wasting my time and I found that the problem was with the mongo package. The find, findone and even insert and update methods all take more than 1 or 2 seconds to complete.
This is the mongo client instantiation
func newmongodb() *mongodb { uri := config.getenvconfig().mongouri database := config.getenvconfig().mongodatabase client, err := mongo.connect(context.todo(), options.client().applyuri(uri)) if err != nil { panic(err) } return &mongodb{ client: client, database: database, } }
This is the function code:
func getmessagebyidfromdb(id string) (*message, error) { conn := database.newmongodb() defer conn.disconnect() filter := map[string]string{ "message_id": id, } var message message start := time.now() err := conn.getcollection(collectionname).findone(context.todo(), filter).decode(&message) elapsed := time.since(start) log.printf("querying messages took %s", elapsed) if err != nil { return nil, err } return &message, nil }
This is the result of function time tracking:
Querying messages took 2.320409472s
This has nothing to do with the internet connection, as I tested the query with python and the request only took 0.003 seconds
I tried changing the version of the package but it didn't work. I also tried reinstalling all packages for the project with the same result.
I also tried creating a search index in the database but didn't get different results. The query also takes more than 2 seconds to complete.
I don't think the query should take more than a few milliseconds to complete.
##mongo.Connect()"only" Initialize by starting the background monitoring goroutineClient
. There may not be a need to connect to a (remote) database.
The above is the detailed content of Why does a simple query take more than 2 seconds using the Golang Mongo driver?. For more information, please follow other related articles on the PHP Chinese website!