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.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
}