一、mongodb封装代码
var client *mongo.Client
func NewMongoDB(ctx context.Context, appUri string) error {
//连接到mongodb
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)
}
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
}
//根据id更新
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
}
//根据id删除一条记录
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
}
//objcetid
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)
}
测试结果:
2022/07/22 11:28:00 mongodb连接成功
2022/07/22 11:28:00 插入单条记录: ObjectID(“62da19400ede9e54c6553272”)
2022/07/22 11:28:00 插入多条记录: [ObjectID(“62da19400ede9e54c6553273”) ObjectID(“62da19400ede9e54c6553274”) ObjectID(“62da19400ede9e54c6553275”) ObjectID(“62da19400ede9e54c6553276”) ObjectID(“62da19400ede9e54c6553277”) ObjectID(“62da19400ede9e54c6553278”) ObjectID(“62da19400ede9e54c6553279”) ObjectID(“62da19400ede9e54c655327a”) ObjectID(“62da19400ede9e54c655327b”) ObjectID(“62da19400ede9e54c655327c”) ObjectID(“62da19400ede9e54c655327d”) ObjectID(“62da19400ede9e54c655327e”) ObjectID(“62da19400ede9e54c655327f”) ObjectID(“62da19400ede9e54c6553280”) ObjectID(“62da19400ede9e54c6553281”) ObjectID(“62da19400ede9e54c6553282”) ObjectID(“62da19400ede9e54c6553283”) ObjectID(“62da19400ede9e54c6553284”) ObjectID(“62da19400ede9e54c6553285”) ObjectID(“62da19400ede9e54c6553286”) ObjectID(“62da19400ede9e54c6553287”) ObjectID(“62da19400ede9e54c6553288”) ObjectID(“62da19400ede9e54c6553289”) ObjectID(“62da19400ede9e54c655328a”) ObjectID(“62da19400ede9e54c655328b”) ObjectID(“62da19400ede9e54c655328c”) ObjectID(“62da19400ede9e54c655328d”) ObjectID(“62da19400ede9e54c655328e”) ObjectID(“62da19400ede9e54c655328f”) ObjectID(“62da19400ede9e54c6553290”) ObjectID(“62da19400ede9e54c6553291”) ObjectID(“62da19400ede9e54c6553292”) ObjectID(“62da19400ede9e54c6553293”) ObjectID(“62da19400ede9e54c6553294”) ObjectID(“62da19400ede9e54c6553295”) ObjectID(“62da19400ede9e54c6553296”) ObjectID(“62da19400ede9e54c6553297”) ObjectID(“62da19400ede9e54c6553298”) ObjectID(“62da19400ede9e54c6553299”) ObjectID(“62da19400ede9e54c655329a”) ObjectID(“62da19400ede9e54c655329b”) ObjectID(“62da19400ede9e54c655329c”) ObjectID(“62da19400ede9e54c655329d”) ObjectID(“62da19400ede9e54c655329e”) ObjectID(“62da19400ede9e54c655329f”) ObjectID(“62da19400ede9e54c65532a0”) ObjectID(“62da19400ede9e54c65532a1”) ObjectID(“62da19400ede9e54c65532a2”) ObjectID(“62da19400ede9e54c65532a3”) ObjectID(“62da19400ede9e54c65532a4”) ObjectID(“62da19400ede9e54c65532a5”) ObjectID(“62da19400ede9e54c65532a6”) ObjectID(“62da19400ede9e54c65532a7”) ObjectID(“62da19400ede9e54c65532a8”) ObjectID(“62da19400ede9e54c65532a9”) ObjectID(“62da19400ede9e54c65532aa”) ObjectID(“62da19400ede9e54c65532ab”) ObjectID(“62da19400ede9e54c65532ac”) ObjectID(“62da19400ede9e54c65532ad”) ObjectID(“62da19400ede9e54c65532ae”) ObjectID(“62da19400ede9e54c65532af”) ObjectID(“62da19400ede9e54c65532b0”) ObjectID(“62da19400ede9e54c65532b1”) ObjectID(“62da19400ede9e54c65532b2”) ObjectID(“62da19400ede9e54c65532b3”) ObjectID(“62da19400ede9e54c65532b4”) ObjectID(“62da19400ede9e54c65532b5”) ObjectID(“62da19400ede9e54c65532b6”) ObjectID(“62da19400ede9e54c65532b7”) ObjectID(“62da19400ede9e54c65532b8”) ObjectID(“62da19400ede9e54c65532b9”) ObjectID(“62da19400ede9e54c65532ba”) ObjectID(“62da19400ede9e54c65532bb”) ObjectID(“62da19400ede9e54c65532bc”) ObjectID(“62da19400ede9e54c65532bd”) ObjectID(“62da19400ede9e54c65532be”) ObjectID(“62da19400ede9e54c65532bf”) ObjectID(“62da19400ede9e54c65532c0”) ObjectID(“62da19400ede9e54c65532c1”) ObjectID(“62da19400ede9e54c65532c2”) ObjectID(“62da19400ede9e54c65532c3”) ObjectID(“62da19400ede9e54c65532c4”) ObjectID(“62da19400ede9e54c65532c5”) ObjectID(“62da19400ede9e54c65532c6”) ObjectID(“62da19400ede9e54c65532c7”) ObjectID(“62da19400ede9e54c65532c8”) ObjectID(“62da19400ede9e54c65532c9”) ObjectID(“62da19400ede9e54c65532ca”) ObjectID(“62da19400ede9e54c65532cb”) ObjectID(“62da19400ede9e54c65532cc”) ObjectID(“62da19400ede9e54c65532cd”) ObjectID(“62da19400ede9e54c65532ce”) ObjectID(“62da19400ede9e54c65532cf”) ObjectID(“62da19400ede9e54c65532d0”) ObjectID(“62da19400ede9e54c65532d1”) ObjectID(“62da19400ede9e54c65532d2”) ObjectID(“62da19400ede9e54c65532d3”) ObjectID(“62da19400ede9e54c65532d4”) ObjectID(“62da19400ede9e54c65532d5”)]
查询单条记录: {“Id”:”62da19400ede9e54c6553272″,”Title”:”test”,”Author”:”author test”,”YearPublished”:9999}
查询多条记录: [{“Id”:”62da19400ede9e54c6553278″,”Title”:”test_6″,”Author”:”author test 6″,”YearPublished”:6},{“Id”:”62da19400ede9e54c6553279″,”Title”:”test_7″,”Author”:”author test 7″,”YearPublished”:7},{“Id”:”62da19400ede9e54c655327a”,”Title”:”test_8″,”Author”:”author test 8″,”YearPublished”:8},{“Id”:”62da19400ede9e54c655327b”,”Title”:”test_9″,”Author”:”author test 9″,”YearPublished”:9}]
更新数量 : 1
三、源代码地址: 源码
原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/276031.html