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
}
在初始化方法中调用
// ===========================
// =初始化Mongodb连接
mdb, err := conf.InitMongoDB()
global.MDB = mdb // 将db对象挂在到全局
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
}
// 将 res.InsertedId 转换为字符串
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 类型")
}
// 将字符串转换回ObjecrId primitive.ObjectIDFromHex
// oid, err := primitive.ObjectIDFromHex("64d492bbdc2330b9e0fdfcc1")
// filter := bson.M{"_id": oid}
// err = collection.FindOne(context.Background(), filter).Decode(&iRecord)
return err
}
查找多条数据
//opts := options.Find().SetSort(bson.M{"enrollment": -1})
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========")
文章来源地址https://www.toymoban.com/news/detail-643573.html
文章来源:https://www.toymoban.com/news/detail-643573.html
到了这里,关于go练习 day02的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!