local mongodb url
To connect to a local MongoDB database in Go, you need to follow these steps:
- Import the necessary packages:
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
In this step, we import the required packages for working with MongoDB in Go. The context
package is used for managing the execution context, the fmt
package is used for printing messages, the log
package is used for logging, and the time
package is used for working with time-related operations. The go.mongodb.org/mongo-driver/mongo
package provides the MongoDB driver for Go, and the go.mongodb.org/mongo-driver/mongo/options
package provides options for configuring the MongoDB connection.
- Establish a connection to the MongoDB database:
func main() {
// Set up a context
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Set up MongoDB connection options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
// Close the connection
err = client.Disconnect(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Disconnected from MongoDB!")
}
In this step, we set up a context with a timeout of 10 seconds using the context.WithTimeout
function. This is used to manage the execution context and ensure that the connection does not hang indefinitely. We then create MongoDB connection options using the options.Client().ApplyURI
function, specifying the URL of the local MongoDB instance (mongodb://localhost:27017
). We connect to MongoDB using the mongo.Connect
function, passing in the context and connection options. Next, we check the connection using the client.Ping
function. If the connection is successful, we print a message indicating that we are connected to MongoDB. Finally, we disconnect from MongoDB using the client.Disconnect
function and print a message indicating that we are disconnected.
- Run the program:
go run main.go
After completing the above steps, you can run the Go program using the go run
command followed by the name of the Go source file (main.go
in this example). This will execute the program and establish a connection to the local MongoDB database.
Please note that you will need to have MongoDB installed and running on your local machine for this code to work.