GoLang 操作MongoDB数据库
数据库中的数据结构
定义的结构体
bson:"xxx"用来映射在MongoDB中的名称,如果不写默认小写
type Student struct {
Name string `bson:"Name"`
Age int `bson:"Age"`
Sex bool `bson:"Sex"`
IsDelete bool `bson:"IsDelete"`
}
下载对应操作数据库的包
封装操作MongoDB数据的结构体
type MongoHelper struct {
Options *options.ClientOptions
Client *mongo.Client
DBName string
CollectionName string
IsConnected bool
Url string
}
const TIME_OUT = 10
func (mh *MongoHelper) Connect(url string) error {
if mh.IsConnected {
return errors.New("[MongoDB] IsConnected Not Again Connect")
}
mh.Url = url
mh.Options = options.Client().ApplyURI(url)
client, err := mongo.Connect(context.TODO(), mh.Options)
if err != nil {
fmt.Println("[MongoDB] Connect Error:", err)
return err
}
mh.Client = client
err = client.Ping(context.TODO(), nil)
if err != nil {
fmt.Println("[MongoDB] Connect Ping Error:", err)
return err
}
fmt.Println("[MongoDB] Connect Success!")
mh.IsConnected = true
return nil
}
func (mh *MongoHelper) FindAll() ([]bson.M, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
cur, err := collection.Find(ctx, bson.D{})
if err != nil {
fmt.Println("[MongoDB] FindAll Error:", err)
return nil, err
}
defer cur.Close(ctx)
retValue := make([]bson.M, 0, 50)
for cur.Next(ctx) {
var result bson.D
err = cur.Decode(&result)
if err != nil {
fmt.Println("[MongoDB] Decode Error:", err)
return nil, err
}
retValue = append(retValue, result.Map())
}
return retValue, nil
}
func (mh *MongoHelper) FindMany(filter bson.D) ([]bson.M, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
cur, err := collection.Find(ctx, filter)
if err != nil {
fmt.Println("[MongoDB] Find Error:", err)
return nil, err
}
defer cur.Close(ctx)
retValue := make([]bson.M, 0, 50)
for cur.Next(ctx) {
var result bson.D
err = cur.Decode(&result)
if err != nil {
fmt.Println("[MongoDB] Decode Error:", err)
return nil, err
}
retValue = append(retValue, result.Map())
}
return retValue, nil
}
func (mh *MongoHelper) InsertOne(document any) (primitive.ObjectID, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return primitive.ObjectID{}, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.InsertOne(ctx, document)
if err != nil {
fmt.Println("[MongoDB] InsertOne Error: ", err)
return primitive.ObjectID{}, err
}
return result.InsertedID.(primitive.ObjectID), nil
}
func (mh *MongoHelper) InsertMany(document []any) ([]primitive.ObjectID, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.InsertMany(ctx, document)
if err != nil {
fmt.Println("[MongoDB] InsertMany Error: ", err)
return nil, err
}
slice := make([]primitive.ObjectID, 0, len(result.InsertedIDs))
for i := 0; i < len(result.InsertedIDs); i++ {
slice = append(slice, result.InsertedIDs[i].(primitive.ObjectID))
}
return slice, nil
}
func (mh *MongoHelper) UpdateByID(id primitive.ObjectID, update bson.D) (*mongo.UpdateResult, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.UpdateByID(ctx, id, update)
if err != nil {
fmt.Println("[MongoDB] UpdateByID Error: ", err)
return nil, err
}
return result, nil
}
func (mh *MongoHelper) UpdateOne(filter bson.D, update bson.D) (*mongo.UpdateResult, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.UpdateOne(ctx, filter, update)
if err != nil {
fmt.Println("[MongoDB] UpdateOne Error: ", err)
return nil, err
}
return result, nil
}
func (mh *MongoHelper) UpdateMany(filter bson.D, update bson.D) (*mongo.UpdateResult, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.UpdateMany(ctx, filter, update)
if err != nil {
fmt.Println("[MongoDB] UpdateMany Error: ", err)
return nil, err
}
return result, nil
}
func (mh *MongoHelper) DeleteOne(filter bson.D, isDelete bool) (*mongo.DeleteResult, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
if isDelete {
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.DeleteOne(ctx, filter)
if err != nil {
fmt.Println("[MongoDB] DeleteOne Error: ", err)
return nil, err
}
return result, nil
} else {
update := bson.D{}
result, err := mh.UpdateOne(filter, update)
if err != nil {
fmt.Println("[MongoDB] DeleteOne IsDelete Error: ", err)
return nil, err
}
return &mongo.DeleteResult{DeletedCount: result.ModifiedCount}, nil
}
}
func (mh *MongoHelper) DeleteMany(filter bson.D, isDelete bool) (*mongo.DeleteResult, error) {
if !mh.IsConnected {
connectError := mh.Connect(mh.Url)
if connectError != nil {
return nil, connectError
}
}
if isDelete {
ctx, cancel := context.WithTimeout(context.Background(), TIME_OUT*time.Second)
defer cancel()
collection := mh.Client.Database(mh.DBName).Collection(mh.CollectionName)
result, err := collection.DeleteMany(ctx, filter)
if err != nil {
fmt.Println("[MongoDB] DeleteMany Error: ", err)
return nil, err
}
return result, nil
} else {
update := bson.D{}
result, err := mh.UpdateMany(filter, update)
if err != nil {
fmt.Println("[MongoDB] DeleteMany IsDelete Error: ", err)
return nil, err
}
return &mongo.DeleteResult{DeletedCount: result.ModifiedCount}, nil
}
}
func NewMongoHelper(dbName, collectionName string) *MongoHelper {
return &MongoHelper{
DBName: dbName,
CollectionName: collectionName,
IsConnected: false,
}
}
|