Skip to content

Commit

Permalink
增加ListWithFields
Browse files Browse the repository at this point in the history
  • Loading branch information
yanue committed Aug 2, 2024
1 parent 6026dec commit a4641a8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type IMgo interface {
GetOneByMap(result any, where map[string]any, sorts ...map[string]int) (err error)
GetAllByMap(results any, where map[string]any, sorts ...map[string]int) (err error)
List(results any, where map[string]any, page, size int, sorts ...map[string]int) (err error)
ListWithFields(results any, where map[string]any, page, size int, _sort map[string]int, fields []string) (err error)
Aggregate(pipeStr string, results any) error
CreateIndex(keys bson.D, Unique bool) (string, error)
DropIndex(name string) error
Expand Down
30 changes: 30 additions & 0 deletions mgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type IMgo interface {
GetOneByMap(result any, where map[string]any, sorts ...map[string]int) (err error)
GetAllByMap(results any, where map[string]any, sorts ...map[string]int) (err error)
List(results any, where map[string]any, page, size int, sorts ...map[string]int) (err error)
ListWithFields(results any, where map[string]any, page, size int, _sort map[string]int, fields []string) (err error)
Aggregate(pipeStr string, results any) error
CreateIndex(keys bson.D, Unique bool) (string, error)
DropIndex(name string) error
Expand Down Expand Up @@ -280,6 +281,35 @@ func (s *Mgo) List(results any, where map[string]any, page, size int, sorts ...m
return
}

func (s *Mgo) ListWithFields(results any, where map[string]any, page, size int, _sort map[string]int, fields []string) (err error) {
// page从1开始
if page > 1 {
page--
} else {
page = 0
}
opts := options.Find()
opts.SetLimit(int64(size))
opts.SetSkip(int64(page * size))
opts.SetSort(_sort)
if len(fields) > 0 {
var projection = make(bson.M, 0)
for _, s2 := range fields {
projection[s2] = 1
}
opts.SetProjection(projection)
}
var ctx = context.Background()
cur, err := s.GetCollection().Find(ctx, where, opts)
if err != nil {
return
}
defer cur.Close(ctx)
// 解析结果
err = cur.All(ctx, results)
return
}

// 更新数据 - 通过map匹配字段

func (s *Mgo) Update(id any, input map[string]any) error {
Expand Down

0 comments on commit a4641a8

Please sign in to comment.