I have written the below program (sample for connection & query run) and not Disconnect the client to check open files with mongodb query. When I use simple connection & after than 10 queries in loop then it will open 3 resources. 2 for connection & 1 for multiple queries that I will run with that client.
But when I use convert the same program with go-routines then open connections increases 7-8. Can you please expalin how mongodb open resources ? & why pooling not work as expected in case of go routine.
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"gopkg.in/mgo.v2/bson"
)
func main() {
// Create a MongoDB connection
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
// defer client.Disconnect(context.Background()) // Close the connection when done
// Ping the MongoDB server and check for errors
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
// Get a pointer to the database and collection
db := client.Database("test")
collection := db.Collection("users")
// Run a query on the collection
// For example, insert a document
res, err := collection.InsertOne(context.Background(), map[string]string{"name": "Alice", "age": "25"})
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted document with ID:", res.InsertedID)
var resp bson.M
err = collection.FindOne(context.TODO(), bson.M{"_id": res.InsertedID}).Decode(&res)
fmt.Println("res", resp, err)
}