为了账号安全,请及时绑定邮箱和手机立即绑定

多条件获取 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 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信