亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用mongodb/mongo-go-driver進行高效分頁

如何使用mongodb/mongo-go-driver進行高效分頁

Go
浮云間 2023-04-17 16:35:01
_id我在下面的文章中讀到,使用 的自然順序執行分頁效率更高,因為 skip 總是從集合的開頭開始。MongoDB 中快速高效的分頁// Page 1db.students.find().limit(10)// Page 2last_id = ...  # logic to get last_iddb.students.find({'_id': {'$gt': last_id}}).limit(10)但我不知道如何使用mongodb/mongo-go-driver.
查看完整描述

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


查看完整回答
反對 回復 2023-04-17
?
慕慕森

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)

...

}


查看完整回答
反對 回復 2023-04-17
?
瀟瀟雨雨

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用另一個索引字段替換該字段。


查看完整回答
反對 回復 2023-04-17
  • 3 回答
  • 0 關注
  • 314 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號