go中使用mongodb实现增删改查
连接mongodb
yaml配置
mongodb:
uri: mongodb://localhost:27017
初始化连接
package conf
import (
"context"
"fmt"
"time"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func InitMongoDB() (*mongo.Client, error){
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(viper.GetString("mongodb.uri")))
if err != nil {
fmt.Printf("Mongodb 连接失败: %v", err)
return nil, err
}
fmt.Println("Mongodb 连接成功")
return client, nil
}
在初始化方法中调用
mdb, err := conf.InitMongoDB()
global.MDB = mdb
if err != nil {
initErr = utils.AppendError(initErr, err)
}
在DAO中挂载到BaseDao上
package dao
import (
"king/global"
"go.mongodb.org/mongo-driver/mongo"
"gorm.io/gorm"
)
type BaseDao struct {
Orm *gorm.DB
MDB *mongo.Client
}
func NewBaseDao() BaseDao {
return BaseDao{
Orm: global.DB,
MDB: global.MDB,
}
}
新增操作:添加一条记录
func (m *RecordDao) AddRecord(iRecordAddDTO *dto.RecordAddDTO) error{
var iRecord model.Record
iRecordAddDTO.ConverToModel(&iRecord)
collection := m.MDB.Database("lowcode").Collection("lowcode")
res, err := collection.InsertOne(context.Background(), iRecord)
if err != nil {
fmt.Println(err)
return err
}
if id, ok := res.InsertedID.(primitive.ObjectID); ok {
insertedIdString := id.Hex()
iRecordAddDTO.ID = insertedIdString
fmt.Println("Inserted ID:", insertedIdString)
} else {
fmt.Println("无法将 InsertedID 转换为 primitive.ObjectID 类型")
}
return err
}
查找多条数据
filter := bson.M{"_id": "64d492bbdc2330b9e0fdfcc1"}
res, err := collection.Find(context.Background(), filter)
res.All(context.TODO(), &resRecords)
for _, result := range resRecords {
fmt.Println(result, "-=-=====-----==1~~~~")
}
插入多条数据
type Person struct {
name string
age int
hobby []string
}
p1 := Person{
name: "zs",
age: 16,
hobby: []string{"sport", "play"}
}
p2 := Person{
name: "ls",
age: 20,
hobby: []string{"write", "play"}
}
pList := []interface{}{p1, p2}
ior, err := collection.InsertMany(context.Background(), pList)
更新数据
t := bson.M{"_id": oid}
update := bson.M{"$set": bson.M{"title": "更新明细任务编号"}}
result, err := collection.UpdateOne(context.Background(), t, update)
fmt.Println(result, "result========")