GoFrame MongoDB Example
Github Source: https://github.com/gogf/examples/tree/main/nosql/mongodb
This example demonstrates how to use MongoDB with GoFrame framework.
Overview
This example shows:
- How to configure
MongoDBconnection usingYAMLconfiguration - How to create a
MongoDBclient - Basic
MongoDBoperations (INSERT,FIND,UPDATE) - How to use
BSONfor document operations
Requirements
Go 1.15or higherMongoDBserverGoFrame v2
Configuration
The MongoDB configuration is stored in config.yaml:
mongo:
database: "user"
address: "mongodb://127.0.0.1:27017/test?retryWrites=true"
You can modify these settings according to your MongoDB server configuration.
Running MongoDB with Docker
If you don't have MongoDB installed locally, you can quickly start a MongoDB instance using Docker:
# Run MongoDB container
docker run --name mongo-test -p 27017:27017 -d mongo:latest
# Verify the container is running
docker ps
# If you need to stop the container later
docker stop mongo-test
# If you need to remove the container
docker rm mongo-test
For MongoDB with authentication:
# Run MongoDB with authentication
docker run --name mongo-test -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=password -d mongo:latest
# Remember to update config.yaml accordingly:
# mongo:
# database: "user"
# address: "mongodb://admin:password@127.0.0.1:27017/test?retryWrites=true"
Running the Example
- Make sure your
MongoDBserver is running - Update the
config.yamlif needed - Run the example:
go run main.go
Code Structure
main.go: Contains the main logic andMongoDBclient initializationconfig.yaml:MongoDBconfiguration file
Features
MongoDBclient initialization with error handling- Configuration management using
GoFrame's configuration system - Basic
MongoDBoperations demonstration - Proper error handling and logging
- Use of
BSONtags for document mapping
Further Reading
For more advanced MongoDB usage, please refer to the official MongoDB Go driver github.com/mongodb/mongo-go-driver.
Notes
- The example uses the official
MongoDBGo driver - All operations are performed with context for proper cancellation and timeout handling
- The code includes proper error handling and logging