首頁 > 後端開發 > Golang > 主體

過濾查詢 mongodb Golang

WBOY
發布: 2024-02-12 08:33:18
轉載
736 人瀏覽過

过滤查询 mongodb Golang

php小編西瓜今天要為大家介紹的是關於過濾查詢mongodb的Golang實作。在使用mongodb資料庫進行資料查詢時,我們經常需要對查詢結果進行過濾,以滿足特定的條件。 Golang作為一種強大的程式語言,提供了豐富的mongodb驅動程式庫,可以輕鬆實現過濾查詢功能。接下來,我們將詳細介紹如何在Golang中使用mongodb進行過濾查詢,幫助大家更好地應用並理解這項功能。

問題內容

我正在嘗試取得與特定查詢相符的資料列表,但收到此錯誤

"(atlaserror) merchant is not allowed or the syntax is incorrect, see
the atlas documentation for more information"
登入後複製
func ...

var result []*model.Package

    ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
    defer cancel()

    tokenData, err := middleware.CtxValue(ctx)

    if err != nil {
        return nil, err
    }

    orQuery := []bson.M{}
    merchant := "abc"
    completedQuery := bson.M{"status": "completed"}
    cancelledQuery := bson.M{"status": "cancelled"}
    orQuery = append(
        orQuery,
        cancelledQuery,
        completedQuery)
    limit64 := int64(limit)
    page64 := int64(page)
    match := bson.M{"$match": bson.M{"$nor": orQuery}}
    var filterQuery primitive.M

    if tokenData.Role == "admin" && merchant != nil {
        filterQuery = bson.M{"merchant": bson.M{"id": merchant}}
    } else {
        filterQuery = bson.M{"user": bson.M{"id": tokenData.Id}}
    }
    paginatedData, err1 := paginate.New(r.Collection).Context(ctx).Limit(limit64).Page(page64).Aggregate(match, filterQuery)
    if err1 != nil {
        return nil, err1
    }


...
登入後複製

解決方法

filterquery,似乎包含{ "merchant" : { "id" : "abc" } }#,被單獨傳遞給.aggregate()。但是聚合框架期望接收代表一系列管道階段的東西。 文件中概述了每個階段,預計以 $ 字元開頭,例如 $match 階段。

目前資料庫正在嘗試將 merchant 作為管道的 options 進行處理(請參閱 這裡此處)。但這樣的選項不存在,因此出現錯誤訊息。

要解決此問題,您應該將 filterquery 邏輯合併到您正在建置和傳遞的現有 match 變數/階段中。或者,您可以將 filterquery 包裝在不同的 $match 中,然後將它們(作為單一參數)傳遞給 .aggregate()

此範例顯示他們建立了多個階段並且然後透過mongo.pipeline{...}:

將它們一起提交給.aggregate()
// create the stages
matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{
    {"price", 1},
    {"toppings", 1}},
}}
limitStage := bson.D{{"$limit", 2}}

// pass the stage into a pipeline
// pass the pipeline as the second paramter in the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})
登入後複製

以上是過濾查詢 mongodb Golang的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!