记录一次分页查询
借鉴原文:golang mongodb 实现分页_zhngxin的博客-CSDN博客
import (
"context"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MgoSession struct {
Session *mongo.Client
Database string
}
// Find
// @Description: 查询多条数据
func (db *MgoSession) Find(collection string, selector bson.M, limit, page int64, schema interface{}) error {
c := db.GetCollection(collection)
// 一定要初始化,否则报错,网上很多文章都没有做这一步
var findoptions *options.FindOptions = &options.FindOptions{}
if limit > 0 {
findoptions.SetLimit(limit)
findoptions.SetSkip((limit * page) - page)
}
cur, err := c.Find(context.Background(), selector, findoptions)
if err != nil {
return err
}
defer cur.Close(context.Background())
return cur.All(context.Background(), schema)
}
// 调用
var passesList []model.Passes
err := db.Find("collectionName", bson.M{"uid":"12345678"}, 1, 10, &passesList)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)