一、封装代码
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)