3 回答

TA貢獻1858條經驗 獲得超8個贊
你可以創建一個新的函數,不要忘記傳遞 http.writer 來讀取參數。
func Pagination(r *http.Request, FindOptions *options.FindOptions) (int64, int64) {
if r.URL.Query().Get("page") != "" && r.URL.Query().Get("limit") != "" {
page, _ := strconv.ParseInt(r.URL.Query().Get("page"), 10, 32)
limit, _ := strconv.ParseInt(r.URL.Query().Get("limit"), 10, 32)
if page == 1 {
FindOptions.SetSkip(0)
FindOptions.SetLimit(limit)
return page, limit
}
FindOptions.SetSkip((page - 1) * limit)
FindOptions.SetLimit(limit)
return page, limit
}
FindOptions.SetSkip(0)
FindOptions.SetLimit(0)
return 0, 0
}
只是打電話
Pagination(r, options)
例子
options := options.Find()
page, limit := parameter.Pagination(r, options)
// page, limit as response for header payload

TA貢獻1856條經驗 獲得超17個贊
如果不需要分頁,則設置 page=0 和 limit=0。
func GetUsers (page, limit int) {
filter := bson.D{{}} // selects all documents
options := new(options.FindOptions)
if limit != 0 {
if page == 0 {
page = 1
}
options.SetSkip(int64((page - 1) * limit))
options.SetLimit(int64(limit))
}
cursor, err := mongoCollection.Find(context.TODO(), filter, options)
...
}

TA貢獻1833條經驗 獲得超4個贊
cursor.skip?()方法要求服務器從輸入結果集的開頭開始掃描,然后才開始返回結果。隨著偏移量的增加,cursor.skip() 會變慢。雖然范圍查詢可以使用索引來避免掃描不需要的文檔,但與用于cursor.skip()
分頁相比,隨著偏移量的增加,通常會產生更好的性能。
使用當前版本的mongo-go-driver?(v0.0.15)。執行分頁的示例首先顯示最新條目:
func Paginate(collection *mongo.Collection, startValue objectid.ObjectID, nPerPage int64) ([]bson.Document, *bson.Value, error) {
? ? // Query range filter using the default indexed _id field.?
? ? filter := bson.VC.DocumentFromElements(
? ? ? ? bson.EC.SubDocumentFromElements(
? ? ? ? ? ? "_id",
? ? ? ? ? ? bson.EC.ObjectID("$gt", startValue),
? ? ? ? ),
? ? )
? ? var opts []findopt.Find
? ? opts = append(opts, findopt.Sort(bson.NewDocument(bson.EC.Int32("_id", -1))))
? ? opts = append(opts, findopt.Limit(nPerPage))
? ? cursor, _ := collection.Find(context.Background(), filter, opts...)
? ? var lastValue *bson.Value
? ? var results []bson.Document
? ? for cursor.Next(context.Background()) {
? ? ? ? elem := bson.NewDocument()
? ? ? ? err := cursor.Decode(elem)
? ? ? ? if err != nil {
? ? ? ? ? ? return results, lastValue, err
? ? ? ? }
? ? ? ? results = append(results, *elem)
? ? ? ? lastValue = elem.Lookup("_id")
? ? }
? ? return results, lastValue, nil
}
上面調用分頁函數的例子:
database := client.Database("databaseName")
collection := database.Collection("collectionName")
startObjectID, _ := objectid.FromHex("5bbafea2b5e14ee3a298fa4a")
// Paginate only the latest 20 documents?
elements, lastID, err := Paginate(collection, startObjectID, 20)
for _, e := range elements {
? ? fmt.Println(&e)
}
// Last seen ObjectID can be used to call next Paginate()?
fmt.Println("Last seen ObjectID: ", lastID.ObjectID())
請注意,您還可以_id用另一個索引字段替換該字段。
- 3 回答
- 0 關注
- 314 瀏覽
添加回答
舉報