GO操作mongo数据库实战
主要是mongo官方文档抄过来的,加上一些自己简单的话术
先决条件
有go环境和mongo环境
创建好go mod文档,导入驱动
require go.mongodb.org/mongo-driver
写个demo
创建一个main.go
导入本次需要的包,和写上一个结构体做案例
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// You will be using this Trainer type later in the program
type Trainer struct {
Name string
Age int
City string
}
连接测试
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
//最后可能也需要关闭连接
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
指定操作集合以及数据库
//test数据库下的trainers集合
collection := client.Database("test").Collection("trainers")
插入
ash := Trainer{"Ash", 10, "Pallet Town"}
//这里可以使用InsertMany来插入多条
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
更新
//更新查询删除的时候会用到filter
filter := bson.D{{"name", "Ash"}}
//更新规则
update := bson.D{
{"$inc", bson.D{
{"age", 1},
}},
}
//这儿只更新一条
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
查找
var result Trainer
//这儿只查找一条
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
//查找多条
findOptions := options.Find()
findOptions.SetLimit(3)
// Here's an array in which you can store the decoded documents
var results []*Trainer
// Passing bson.D{{}} as the filter matches all documents in the collection
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
if err != nil {
log.Fatal(err)
}
// Finding multiple documents returns a cursor
// Iterating through the cursor allows us to decode documents one at a time
for cur.Next(context.TODO()) {
// create a value into which the single document can be decoded
var elem Trainer
err := cur.Decode(&elem)
if err != nil {
log.Fatal(err)
}
results = append(results, &elem)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
// Close the cursor once finished
cur.Close(context.TODO())
fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)
for i := 0; i < len(results); i++ {
fmt.Println(results[i])
}
删除
deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)