提取具有多个条件的MongoDB收集记录

I want to fetch mongodb collection with multiple conditions but I am getting the error:

panic: Failed to parse: filter: [ { visibility: { $eq: "4" } }, { 
discontinued: { $ne: "1" } }, { status: { $eq: "1" } } ]. 'filter' field 
must be of BSON type Object.

The code is as follow:

package main

import (
    "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"`
    MetaDescription         string  `bson:"meta_description"`
    Image                   string  `bson:"image"`
    SmallImage              string  `bson:"small_image"`
    Thumbnail               string  `bson:"thumbnail"`
    Gallery                 string  `bson:"gallery"`
    UrlKey                  string  `bson:"url_key"`
    UrlPath                 string  `bson:"url_path"`
    Mpn                     string  `bson:"mpn"`
    ProductListingAds       string  `bson:"product_listing_ads"`
    Color                   string  `bson:"color"`
    Price                   float32 `bson:"price"`
    Cost                    float32 `bson:"cost"`
    TierPriceForBundle      float32 `bson:"tier_price_for_bundle"`
    RegularPrice            float32 `bson:"regular_price"`
    SpecialFromDate         string  `bson:"special_from_date"`
    Description             string  `bson:"description"`
    MetaKeyword             string  `bson:"meta_keyword"`
    Dimensions              string  `bson:"dimensions"`
    Features                string  `bson:"features"`
    DeliveryPopupMessage    string  `bson:"delivery_popup_message"`
    CreatedAt               string  `bson:"created_at"`
    UpdatedAt               string  `bson:"updated_at"`
}

I am trying to fetch records based on multiple aggregate functions from mongodb with go. Basically if we remove the square brackets and try with mongo command it works, but how to fix this in go?

Thank You.

dqrzot2791
dqrzot2791 输出格式如下:[]bson.M以下面的格式显示:[{已停产:{$eq:“1”}}},{状态:{$eq:“1”}}},{可见性:{$eq:“4”}}],而正确的格式为:{停产:{$eq:1}},{状态:{$eq:1}},{可见性:{$eq:4}}
大约 2 年之前 回复
doumowu7371
doumowu7371 尝试在运算符上添加“”。更改运算符=$eq,将运算符=“$eq”键入bson.M是map[string]interface{},并在致命日志错误中显示$eq而不是“$eq”ref:godoc.org/gopkg.in/mgo.V2/BSON#m的
大约 2 年之前 回复
doujishan2247
doujishan2247 可以帮助您请访问
大约 2 年之前 回复

1个回答



您将操作</ code>声明为 [] bson.M {} < / code>,因此您将获得一组地图。 </ p>

如果您检查定义</ bson.M {}的a>是一个map [string] interface {}
您只需要向地图添加元素(就您而言,您要执行的操作)。 为此,语法为 yourMap [yourKey] = yourValue </ code>。</ p>

尝试以下代码生成操作循环:</ p>

  operations:= bson.M {} 
for _,val:=范围条件{
var attr,operator,value interface {}
cons:= val。(map [interface {}] interface {})
表示范围cons {
attr = cons [“ attribute”]
运算符= cons [“ operator”]
value = cons [“ value”]

切换运算符{
case“ ==“:
运算符=” $ eq“
case”!=“:
运算符=” $ ne“
case”()“:
运算符=” $ in“
}
}

操作[attr。(string)] = bson.M {operator。(string):value}
}
</ code> </ pre>
</ div>

展开原文

原文

The problem vas you were declaring the operationsas a []bson.M{}, so you're obtaining an array of maps.

If you check the definition of bson.M{} it's a map[string]interface{} You just need to add elements to the map (in your case the operations you want). For do this, the syntax is yourMap[yourKey] = yourValue.

Try the following code for the operations loop generation:

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}
}

douzhi4991
douzhi4991 不用担心@engrhussainahmad我们有一天开始了!
大约 2 年之前 回复
dsxz84851
dsxz84851 其实我是新手。 非常感谢,节省了我很多时间。
大约 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐