目錄
正確答案
首頁 後端開發 Golang 使用 golang for MongoDB 建立分頁篩選器

使用 golang for MongoDB 建立分頁篩選器

Feb 05, 2024 pm 09:15 PM

使用 golang for MongoDB 创建分页过滤器

問題內容

我有一個很大的過濾器,我將提供它的一個片段。我試圖透過異教化過濾器的映射,但收到錯誤訊息

the match filter must be an expression in an object
登入後複製

取得過濾器

func (app *courses) getfilter(filter *filter) ([]bson.m, error) {
    
        pipeline := make([]bson.m, 0)
    
        if filter.all {
            // include all items
        } else {
            // filter items based on the provided criteria
            if filter.beginner {
                pipeline = append(pipeline, bson.m{"tags": "beginner"})
            }
            if filter.advanced {
                pipeline = append(pipeline, bson.m{"tags": "advanced"})
            }
            if filter.go {
                pipeline = append(pipeline, bson.m{"tags": "go"})
            }
        }
    
        return pipeline, nil
    }
登入後複製

處理程序

func (app *courses) coursesallhandler(w http.responsewriter, r *http.request) {
    ctx := context.background()

    clog := log.getloggerfromcontext(ctx)

    p := r.url.query().get("page")
    ps := r.url.query().get("pagesize")

    var filter filter
    err := json.newdecoder(r.body).decode(&filter)
    if err != nil {
        http.error(w, "failed to parse request body", http.statusbadrequest)
        return
    }

    pipeline := make([]bson.m, 0)

    page, _ := strconv.atoi(p)
    pagesize, _ := strconv.atoi(ps)

    // pagination
    skip := (page - 1) * pagesize
    limit := pagesize

    // add filter
    pipeline, err = app.getfilter(&filter)
    if err != nil {
        clog.error(err)
    }
    pipeline = append(pipeline, bson.m{"$match": pipeline})

    // add pagination stages to the pipeline
    pipeline = append(pipeline, bson.m{"$skip": skip})
    pipeline = append(pipeline, bson.m{"$limit": limit})

    res, err := app.repo.getall(ctx, pipeline)
    if err != nil {
        clog.error(err)

        return
    }

    err = app.helper.writejson(w, http.statusok, envelope{"data": res, "metadata": "none"}, nil)
    if err != nil {
        clog.errorctx(err, log.ctx{
            "header":      w.header(),
            "request_url": r.url.string(),
        })
    }

}
登入後複製

如何取得設定為「true」或「false」的值,將它們放入地圖中並在查詢中提交它們以匹配資料庫,就像我在這裡嘗試做的那樣。

// add filter
pipeline, err = app.getfilter(&filter)
if err != nil {
    clog.error(err)
}
pipeline = append(pipeline, bson.m{"$match": pipeline})
登入後複製

----更新----

我現在有:

func (app *courses) coursesallhandler(w http.responsewriter, r *http.request) {
    ctx := context.background()

clog := log.getloggerfromcontext(ctx)

var filter filter
err := json.newdecoder(r.body).decode(&filter)
if err != nil {
    http.error(w, "failed to parse request body", http.statusbadrequest)
    return
}

filter.all = true

pipeline := make([]bson.m, 3)

// add filter
matches, err := app.getfilter(&filter)
if err != nil {
    clog.error(err)
}

pipeline[0] = bson.m{"$skip": 1}
pipeline[1] = bson.m{"$limit": 5}
pipeline[2] = bson.m{"$match": matches}


res, err := app.repo.getall(ctx, pipeline)
if err != nil {
    clog.error(err)

    return
}

err = app.helper.writejson(w, http.statusok, envelope{"data": res, "metadata": "none"}, nil)
if err != nil {
    clog.errorctx(err, log.ctx{
        "header":      w.header(),
        "request_url": r.url.string(),
    })
 }

}
登入後複製

過濾器看起來像

func (app *courses) getfilter(filter *filter) (bson.m, error) {

    match := bson.m{}
    tags := []string{}

    if filter.all {
        // include all items
        tags = append(tags, "beginner")
        tags = append(tags, "intermediate")
        .....
    } else {
        // filter items based on the provided criteria
        if filter.beginner {
            tags = append(tags, "beginner")
        }
        if filter.advanced {
            tags = append(tags, "advanced")
        }
        if filter.go {
            tags = append(tags, "go")
        }
        ........

    }

    match = bson.m{
        "tags": bson.m{"$in": tags},
    }

    return match, nil
}
登入後複製

稍後將在這裡使用..

func (r *CourseRepo) GetAll(ctx context.Context, pipeline []bson.M) ([]Course, error) {
    clog := log.GetLoggerFromContext(ctx)

    cur, err := r.collection.Aggregate(ctx, pipeline)

    ...
登入後複製

但是它是空的。過濾器中的所有內容均已選擇,沒有錯誤。


正確答案


您得到的 匹配過濾器必須是物件 中的表達式,因為$match 需要一個物件(bson.m),但您已經給了slice 物件([]bson.m)

試試這個

func (app *Courses) getFilter(filter *Filter) (bson.M, error) {
    match := bson.M{}
    tags := []string{}

    if filter.All {
        // Include all items
    } else {
        // Filter items based on the provided criteria
        if filter.Beginner {
            tags = append(tags, "beginner")
        }
        if filter.Advanced {
            tags = append(tags, "advanced")

        }
        if filter.Go {
            tags = append(tags, "go")
        }

        match = bson.M{
            "tags": bson.M{"$in": tags},
        }
    }

    return match, nil
}
登入後複製

以上是使用 golang for MongoDB 建立分頁篩選器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

您如何使用PPROF工具分析GO性能? 您如何使用PPROF工具分析GO性能? Mar 21, 2025 pm 06:37 PM

本文解釋瞭如何使用PPROF工具來分析GO性能,包括啟用分析,收集數據並識別CPU和內存問題等常見的瓶頸。

Go的爬蟲Colly中Queue線程的問題是什麼? Go的爬蟲Colly中Queue線程的問題是什麼? Apr 02, 2025 pm 02:09 PM

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

Go語言中用於浮點數運算的庫有哪些? Go語言中用於浮點數運算的庫有哪些? Apr 02, 2025 pm 02:06 PM

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

您如何在GO中編寫單元測試? 您如何在GO中編寫單元測試? Mar 21, 2025 pm 06:34 PM

本文討論了GO中的編寫單元測試,涵蓋了最佳實踐,模擬技術和有效測試管理的工具。

從前端轉型後端開發,學習Java還是Golang更有前景? 從前端轉型後端開發,學習Java還是Golang更有前景? Apr 02, 2025 am 09:12 AM

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

您如何在go.mod文件中指定依賴項? 您如何在go.mod文件中指定依賴項? Mar 27, 2025 pm 07:14 PM

本文討論了通過go.mod,涵蓋規範,更新和衝突解決方案管理GO模塊依賴關係。它強調了最佳實踐,例如語義版本控制和定期更新。

Debian下PostgreSQL監控方法 Debian下PostgreSQL監控方法 Apr 02, 2025 am 07:27 AM

本文介紹在Debian系統下監控PostgreSQL數據庫的多種方法和工具,助您全面掌握數據庫性能監控。一、利用PostgreSQL內置監控視圖PostgreSQL自身提供多個視圖用於監控數據庫活動:pg_stat_activity:實時展現數據庫活動,包括連接、查詢和事務等信息。 pg_stat_replication:監控複製狀態,尤其適用於流複製集群。 pg_stat_database:提供數據庫統計信息,例如數據庫大小、事務提交/回滾次數等關鍵指標。二、借助日誌分析工具pgBadg

See all articles