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

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

多條件獲取 MongoDB 集合記錄

多條件獲取 MongoDB 集合記錄

Go
鴻蒙傳說 2023-04-17 14:48:52
我想獲取具有多個條件的 mongodb 集合,但出現錯誤:panic: Failed to parse: filter: [ { visibility: { $eq: "4" } }, { discontinued: { $ne: "1" } }, { status: { $eq: "1" } } ]. 'filter' field must be of BSON type Object.代碼如下:package mainimport (    "fmt"    "gopkg.in/mgo.v2/bson")func GenerateFeed(headers, attributes interface{}, conditions []interface{}) {    var operations = []bson.M{}    for _, val := range conditions {        var attr, operator, value interface{}        cons := val.(map[interface{}]interface{})        for range cons {            attr     = cons["attribute"]            operator = cons["operator"]            value    = cons["value"]            switch operator {                case "==":                    operator = "$eq"                case "!=":                    operator = "$ne"                case "()":                    operator = "$in"            }        }        operations = append(operations, bson.M{attr.(string):         bson.M{operator.(string): value}})    }    var products []Prod    session := Connect()    collection := session.DB("rfgv2").C("catalog_product_entity_1")    err := collection.Find(operations).All(&products)    CheckError(err)    fmt.Println(products)}type Prod struct {    EntityId                string  `bson:"entity_id"`    Name                    string  `bson:"name"`    TypeId                  string  `bson:"type_id"`    Sku                     string  `bson:"sku"`    Manufacturer            int32   `bson:"manufacturer"`    Status                  int32   `bson:"status"`    Visibility              int32   `bson:"visibility"`    EnableGoogleCheckout    int32   `bson:"enable_google_checkout"`    Delivery                string  `bson:"delivery"`    MetaTitle               string  `bson:"meta_title"`}我正在嘗試使用 go 從 mongodb 獲取基于多個聚合函數的記錄?;旧?,如果我們刪除方括號并嘗試使用 mongo 命令,它就可以工作,但是如何在 go 中解決這個問題?
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

問題在于您將 the 聲明operations為 a?[]bson.M{},因此您獲得了一組地圖。

如果您檢查bson.M{} 的定義,它是一個 map[string]interface{} 您只需要將元素添加到地圖(在您的情況下是您想要的操作)。為此,語法是yourMap[yourKey] = yourValue.

嘗試使用以下代碼生成操作循環:

operations := bson.M{}

for _, val := range conditions {

? ? var attr, operator, value interface{}

? ? cons := val.(map[interface{}]interface{})

? ? for range cons {

? ? ? ? attr? ? ?= cons["attribute"]

? ? ? ? operator = cons["operator"]

? ? ? ? value? ? = cons["value"]


? ? ? ? switch operator {

? ? ? ? ? ? case "==":

? ? ? ? ? ? ? ? operator = "$eq"

? ? ? ? ? ? case "!=":

? ? ? ? ? ? ? ? operator = "$ne"

? ? ? ? ? ? case "()":

? ? ? ? ? ? ? ? operator = "$in"

? ? ? ? }

? ? }

? ? ? ? operations[attr.(string)] = bson.M{operator.(string): value}

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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