golang mongodb 实现分页
实现分页mongodb的官方驱动 mongo-go-driver并不像mgo一样直接。
go
import(
"context"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func Find(database *mongo.Database,collection string,limit,index int64) (data []map[string]interface,err error){
ctx, cannel := context.WithTimeout(context.Background(), time.Minute)
defer cannel()
var findoptions *options.FindOptions
if limit > 0 {
findoptions = &options.FindOptions{}
findoptions.SetLimit(limit)
findoptions.SetSkip(limit * index)
}
cur, err := database.Collection(collection).Find(ctx, bson.M{}, findoptions)
if err != nil {
return nil, err
}
defer cur.Close(context.Background())
err = cur.All(context.Background(), &data)
return
}