一、封装代码
package mongodb
import (
"context"
"log"
"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"
)
var client *mongo.Client
func NewMongoDB(ctx context.Context, appUri string) error {
c, err := mongo.Connect(ctx, options.Client().ApplyURI(appUri))
if err != nil {
return err
}
err = c.Ping(ctx, nil)
if err != nil {
return err
}
client = c
log.Println("mongodb连接成功")
return nil
}
type MongoDB[T any] struct {
database string
collection string
}
func NewMGDB[T any](database string, collection string) *MongoDB[T] {
if client == nil {
log.Fatalln("mongo.Client Not initialized !")
}
return &MongoDB[T]{
database,
collection,
}
}
func (mg *MongoDB[T]) InsertOne(ctx context.Context, value T) *mongo.InsertOneResult {
result, err := mg.getCollection().InsertOne(ctx, value)
if err != nil {
panic(err)
}
return result
}
func (mg *MongoDB[T]) InsertMultiple(ctx context.Context, data []T) *mongo.InsertManyResult {
var array []interface{}
for i := 0; i < len(data); i++ {
array = append(array, data[i])
}
result, err := mg.getCollection().InsertMany(ctx, array)
if err != nil {
panic(err)
}
return result
}
func (mg *MongoDB[T]) FindOne(ctx context.Context, filter filter) (T, error) {
var t T
err := mg.getCollection().FindOne(ctx, filter).Decode(&t)
if err != nil {
return t, err
}
return t, nil
}
func (mg *MongoDB[T]) Find(ctx context.Context, filter filter, limit int64) ([]T, error) {
findOpts := options.Find()
findOpts.SetLimit(limit)
cursor, err := mg.getCollection().Find(ctx, filter, findOpts)
var ts []T
if err != nil {
return ts, err
}
for cursor.Next(ctx) {
var t T
err := cursor.Decode(&t)
if err != nil {
return ts, err
}
ts = append(ts, t)
}
cursor.Close(ctx)
return ts, nil
}
func (mg *MongoDB[T]) UpdateOne(ctx context.Context, filter filter, update interface{}) (int64, error) {
result, err := mg.getCollection().UpdateOne(ctx, filter, bson.M{"$set": update})
return result.ModifiedCount, err
}
func (mg *MongoDB[T]) UpdateOneById(ctx context.Context, id string, update interface{}) (int64, error) {
result, err := mg.getCollection().UpdateOne(ctx, filter{{Key: "_id", Value: mg.ObjectID(id)}}, update)
return result.ModifiedCount, err
}
func (mg *MongoDB[T]) UpdateMany(ctx context.Context, filter filter, update interface{}) (int64, error) {
result, err := mg.getCollection().UpdateMany(ctx, filter, bson.D{{Key: "$set", Value: update}})
return result.ModifiedCount, err
}
func (mg *MongoDB[T]) getCollection() *mongo.Collection {
return client.Database(mg.database).Collection(mg.collection)
}
func (mg *MongoDB[T]) DeleteOne(ctx context.Context, filter filter) (int64, error) {
result, err := mg.getCollection().DeleteOne(ctx, filter)
return result.DeletedCount, err
}
func (mg *MongoDB[T]) DeleteOneById(ctx context.Context, id string) (int64, error) {
result, err := mg.getCollection().DeleteOne(ctx, filter{{Key: "_id", Value: mg.ObjectID(id)}})
return result.DeletedCount, err
}
func (mg *MongoDB[T]) DeleteMany(ctx context.Context, filter filter) (int64, error) {
result, err := mg.getCollection().DeleteMany(ctx, filter)
return result.DeletedCount, err
}
func (mg *MongoDB[T]) ObjectID(id string) primitive.ObjectID {
objectId, err := primitive.ObjectIDFromHex(id)
if err != nil {
log.Fatal(err)
}
return objectId
}
type filter bson.D
func (f filter) GT(key string, value interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$gt", Value: value}}})
return f
}
func (f filter) GTE(key string, value interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$gte", Value: value}}})
return f
}
func (f filter) EQ(key string, value interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$eq", Value: value}}})
return f
}
func (f filter) LT(key string, value interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$lt", Value: value}}})
return f
}
func (f filter) LET(key string, value interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$let", Value: value}}})
return f
}
func (f filter) NE(key string, value interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$ne", Value: value}}})
return f
}
func (f filter) IN(key string, value ...interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$in", Value: value}}})
return f
}
func (f filter) NIN(key string, value ...interface{}) filter {
f = append(f, bson.E{Key: key, Value: bson.D{{Key: "$nin", Value: value}}})
return f
}
func Newfilter() filter {
return filter{}
}
二、测试代码
type Test struct {
Id primitive.ObjectID `bson:"_id"`
Title string `bson:"title"`
Author string `bson:"author"`
YearPublished int64 `bson:"year_published"`
}
func main() {
ctx := context.Background()
err := mongodb.NewMongoDB(ctx, "mongodb://localhost:27017")
if err != nil {
log.Fatalf("%s", err)
return
}
mgdb := mongodb.NewMGDB[Test]("test", "favorite_books")
insertOneResult := mgdb.InsertOne(ctx, Test{
Id: primitive.NewObjectID(),
Title: "test",
Author: "author test",
YearPublished: 9999,
})
log.Printf("插入单条记录: %v \n", insertOneResult.InsertedID)
var tests []Test
for i := 1; i < 100; i++ {
tests = append(tests, Test{
Id: primitive.NewObjectID(),
Title: "test_" + fmt.Sprintf("%d", i),
Author: "author test " + fmt.Sprintf("%d", i),
YearPublished: int64(i),
})
}
insertMultipleResult := mgdb.InsertMultiple(ctx, tests)
log.Printf("插入多条记录: %v \n", insertMultipleResult.InsertedIDs)
filter := mongodb.Newfilter().EQ("title", "test").EQ("author", "author test")
result, err := mgdb.FindOne(ctx, filter)
if err != nil {
log.Fatalf("%s", err)
}
buf, err := json.Marshal(result)
fmt.Printf("查询单条记录: %s\n ", string(buf))
filter = mongodb.Newfilter().GT("year_published", 5).LT("year_published", 10)
results, err := mgdb.Find(ctx, filter, 10)
if err != nil {
log.Fatalf("%s", err)
}
buf, err = json.Marshal(results)
fmt.Printf("查询多条记录: %v\n ", string(buf))
filter = mongodb.Newfilter().EQ("year_published", 9999)
updateCount, err := mgdb.UpdateOne(ctx, filter, map[string]interface{}{
"author": "test 00021",
})
if err != nil {
log.Fatalf("%s", err)
}
fmt.Printf("更新数量 : %d\n", updateCount)
filter = mongodb.Newfilter().IN("year_published", 11, 12, 13)
updateCount, err = mgdb.UpdateMany(ctx, filter, map[string]interface{}{
"author": "update author",
})
if err != nil {
log.Fatalf("%s", err)
}
fmt.Printf("批量更新数量 : %d\n", updateCount)
filter = mongodb.Newfilter().EQ("year_published", 15)
deleteCount, err := mgdb.DeleteOne(ctx, filter)
if err != nil {
log.Fatalf("%s", err)
}
fmt.Printf("单条数据删除数量 : %d\n", deleteCount)
filter = mongodb.Newfilter().IN("year_published", 16, 17, 18)
deleteCount, err = mgdb.DeleteMany(ctx, filter)
if err != nil {
log.Fatalf("%s", err)
}
fmt.Printf("多条数据删除数量 : %d\n", deleteCount)
}