Even the simplest code:
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://standard:example@cluster0.f5yec.mongodb.net/blog-application?retryWrites=true&w=majority"))
if err != nil {
log.Fatal("Error connect to DB: ", err.Error())
}
db := client.Database("blog-application")
fmt.Println(time.Now().Second()) // 9
db.Collection("user").Find(context.Background(), bson.M{})
fmt.Println(time.Now().Second()) // 39
}
takes 30 seconds to run.
Why does it need that long to run? Any help is appreciated!
You have no error checking on the find. Your find fails because your client can't connect to your cluster, and the default server selection timeout is 30 seconds.
"Each database operation takes 30 seconds" is only partially true. Each attempt at a database operation takes 30 seconds before it fails.