Why is a simple query taking more than 2 seconds with Golang Mongo driver?

Daniel Luis

I am coding a golang web service that has a mongo database, I am using the go.mongodb.org/mongo-driver v1.11.6 and a simple query is taking more than 2 seconds to complete. The database has only a few records, is it just for testing, no more than 10 records.

I've been looking for the code part where the time is being wasted and I found that the problem is with the mongo package. The methods Find, FindOne and even Insert and Update are taking 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 the time tracking of the function:

Querying messages took 2.320409472s

It is not about internet connection because I made the query test with python and the request took only 0.003 seconds

I tried to change the version of the package without achieving it. Also I tried to reinstall all the packages of the project, with the same result.

I also tried to create search indexes in database with no different results. The query also take more than 2 seconds to complete.

I think the query shouldn't take more than a few milliseconds to complete.

icza

mongo.Connect() "only" initializes the Client by starting background monitoring goroutines. It may not necessary connect to the (remote) database.

When you then perform queries, they certainly require to build up connections, and that may take seconds.

You may use the Client.Ping() method prior to force connecting to the database and verify that the connection was created successfully, so when you perform queries after that, a connection will be ready.

You may also try to repeat the same query, as after the first query the connection will not be closed but put into a connection pool and reused when needed again (for the second query).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Simple query taking long (~15 seconds)

Update query is taking 2 seconds to update the table

Mongo-go-driver nested query golang

mongo aggregation query in golang with mgo driver

10 Million rows taking 3.50 seconds for a simple type query

Why do I take more than 2 seconds to just do a transaction?

Get actual execution plan for query taking more than hours?

Mysql Query Taking 300 Times More Time Using Simple Wrapper

Why is this query working in the mongo shell but not the node mongo driver?

Why node.js process taking more memory than allocated

Why is my html table taking up more height than necessary?

Why sscanf is taking more than desired value in C?

Why is WSL taking up more disk space than it says it is?

Single row UPDATE query in SQL takes more than 3 seconds

Golang mongo driver performance

Why the program run last much more time than 3 seconds?

SQLite + Flask occasionally taking 10-20 seconds to return simple select query

Below query is taking 2 mins ,can it be tuned more

Retrofit query parameter is not taking values greater than 2^32

SQL query with more than 2 tables

More than 2 ORDER BY in a single query?

getting more records than expected with simple query in postgresql

More than one row returned by a subquery used as an expression on on a simple query?

SQL - Group count by 2 or more columns using union takes more than 2 seconds

Golang mongo-go-driver Beta 1 , using greater than operator

How can I improve this query in postgresql? Its taking more than 48 houers already

Simple query taking long time

Why does a linked list implementation in C show one more malloc than is actually taking place

Why is flexbox's first child taking more space than its own content?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive