GoFrame MongoDB Example
Code 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
MongoDB
connection usingYAML
configuration - How to create a
MongoDB
client - Basic
MongoDB
operations (INSERT
,FIND
,UPDATE
) - How to use
BSON
for document operations
Requirements
Go 1.15
or higherMongoDB
serverGoFrame 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
MongoDB
server is running - Update the
config.yaml
if needed - Run the example:
go run main.go
Code Structure
main.go
: Contains the main logic andMongoDB
client initializationconfig.yaml
:MongoDB
configuration file
Features
MongoDB
client initialization with error handling- Configuration management using
GoFrame
's configuration system - Basic
MongoDB
operations demonstration - Proper error handling and logging
- Use of
BSON
tags 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
MongoDB
Go driver - All operations are performed with context for proper cancellation and timeout handling
- The code includes proper error handling and logging