
go操作mongodb
示例
go
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// User 结构体,对应 MongoDB 中的文档
type User struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Name string `bson:"name"`
Email string `bson:"email"`
Age int `bson:"age,omitempty"`
Active bool `bson:"active,omitempty"`
LastSeen time.Time `bson:"last_seen,omitempty"`
}
func connect() (*mongo.Client, context.Context, context.CancelFunc) {
// 设置上下文,超时 10 秒
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
// MongoDB 连接 URI(根据你的配置修改)
uri := "mongodb://localhost:27017" // 本地
// uri := "mongodb://user:pass@host:port/db" // 远程或带认证
// 创建 MongoDB 客户端
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
log.Fatal("Failed to connect to MongoDB:", err)
}
// 测试连接
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal("Failed to ping MongoDB:", err)
}
fmt.Println("Connected to MongoDB!")
return client, ctx, cancel
}
func insertUser(client *mongo.Client, ctx context.Context) {
collection := client.Database("testdb").Collection("users")
user := User{
Name: "Alice",
Email: "alice@example.com",
Age: 28,
Active: true,
LastSeen: time.Now(),
}
result, err := collection.InsertOne(ctx, user)
if err != nil {
log.Fatal("Insert failed:", err)
}
fmt.Printf("Inserted user with ID: %s\n", result.InsertedID)
}
func findUserByID(client *mongo.Client, ctx context.Context, idStr string) {
collection := client.Database("testdb").Collection("users")
// 将字符串 ID 转换为 ObjectID
objectID, err := primitive.ObjectIDFromHex(idStr)
if err != nil {
log.Fatal("Invalid ID format:", err)
}
var user User
// 查询
err = collection.FindOne(ctx, bson.M{"_id": objectID}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Printf("❌ 未找到 ID 为 %s 的用户\n", idStr)
} else {
log.Fatal("查询出错:", err)
}
return
}
fmt.Printf("✅ 查询到用户: %+v\n", user)
}
func findUsers(client *mongo.Client, ctx context.Context) {
collection := client.Database("testdb").Collection("users")
// 查询所有用户
cursor, err := collection.Find(ctx, bson.M{})
if err != nil {
log.Fatal("Find failed:", err)
}
defer cursor.Close(ctx)
fmt.Println("All users:")
for cursor.Next(ctx) {
var user User
if err := cursor.Decode(&user); err != nil {
log.Fatal("Decode error:", err)
}
fmt.Printf("User: %+v\n", user)
}
if err := cursor.Err(); err != nil {
log.Fatal("Cursor error:", err)
}
}
func findUserByName(client *mongo.Client, ctx context.Context, name string) {
collection := client.Database("testdb").Collection("users")
var user User
err := collection.FindOne(ctx, bson.M{"name": name}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Printf("User '%s' not found\n", name)
} else {
log.Fatal("Query error:", err)
}
return
}
fmt.Printf("Found user: %+v\n", user)
}
func updateUser(client *mongo.Client, ctx context.Context, name string) {
collection := client.Database("testdb").Collection("users")
update := bson.M{
"$set": bson.M{
"age": 29,
"active": false,
"last_seen": time.Now(),
},
}
result, err := collection.UpdateOne(ctx, bson.M{"name": name}, update)
if err != nil {
log.Fatal("Update failed:", err)
}
fmt.Printf("Modified %v document(s)\n", result.ModifiedCount)
}
func deleteUser(client *mongo.Client, ctx context.Context, name string) {
collection := client.Database("testdb").Collection("users")
result, err := collection.DeleteOne(ctx, bson.M{"name": name})
if err != nil {
log.Fatal("Delete failed:", err)
}
fmt.Printf("Deleted %v document(s)\n", result.DeletedCount)
}
func main() {
client, ctx, cancel := connect()
defer cancel()
defer func() {
if err := client.Disconnect(ctx); err != nil {
log.Fatal("Failed to disconnect:", err)
}
}()
// 执行 CRUD 操作
insertUser(client, ctx)
// 替换为实际存在的 _id(12字节或 24位十六进制字符串)
idStr := "670b123456789abcde123456" // 示例 ID
findUserByID(client, ctx, idStr)
findUsers(client, ctx)
findUserByName(client, ctx, "Alice")
updateUser(client, ctx, "Alice")
findUsers(client, ctx)
deleteUser(client, ctx, "Alice")
findUsers(client, ctx) // 再次查询,确认已删除
}