【问题标题】:Issue in mongo query with multiple conditions by using golang使用 golang 在具有多个条件的 mongo 查询中出现问题
【发布时间】:2017-03-08 12:07:07
【问题描述】:

我有一份文件如下-

{ 
    "_id" : "580eef0e4dcc220df897a9cb", 
    "brandId" : 15, 
    "category" : "air_conditioner", 
    "properties" : [
        {
            "propertyName" : "A123", 
            "propertyValue" : "A123 678"
        }, 
        {
            "propertyName" : "B123", 
            "propertyValue" : "B123 678"
        }, 
        {
            "propertyName" : "C123", 
            "propertyValue" : "C123 678"
        }
    ]
}

在此,properties 数组可以有多个元素。 当我通过我的 API 执行搜索时, 理想情况下,我会在 POST 请求的正文中传递一个类似于 properties 的数组 -

{ 
    "brandId" : 15, 
    "category" : "air_conditioner", 
    "properties" : [
        {
            "propertyName" : "A123", 
            "propertyValue" : "A123 678"
        }, 
        {
            "propertyName" : "B123", 
            "propertyValue" : "B123 678"
        }, 
        {
            "propertyName" : "C123", 
            "propertyValue" : "C123 678"
        }
    ]
}

我有一个结构来接收和解码这些信息 -

type Properties struct {
    PropertyName  string `json:"propertyName" bson:"propertyName"`
    PropertyValue string `json:"propertyValue" bson:"propertyValue"`
}

type ReqInfo struct {
    BrandID      int             `json:"brandId" bson:"brandId"`
    Category     string          `json:"category" bson:"category"`
    Properties   []Properties    `json:"properties" bson:"properties"`
}

我还可以对各种 properties 执行 mongodb $and 操作,只有当它们都匹配时,才会返回文档。 这里的问题是properties数组中的元素个数不固定。 我需要能够发送只是

{ 
    "brandId" : 15, 
    "category" : "air_conditioner", 
    "properties" : [
        {
            "propertyName" : "A123", 
            "propertyValue" : "A123 678"
        }
    ]
}

并检索所有匹配的文档(不仅仅是一个)。

我尝试使用 for 循环创建可变大小 bson.M,具体取决于作为输入接收的 properties 数组的大小,但无法找到正确的方法!

应该如何处理?

【问题讨论】:

    标签: javascript arrays mongodb go mgo


    【解决方案1】:

    我能够通过单独构造 $and 部分来实现这一点 -

    var AndQuery []map[string]interface{}
    for i := 0; i < len(body.Properties); i++ {
        log.Println(body.Properties[i])
        currentCondition := bson.M{"properties": bson.M{"$elemMatch": bson.M{"propertyName": body.Properties[i].PropertyName, "propertyValue": body.Properties[i].PropertyValue}}}
        AndQuery = append(AndQuery, currentCondition)
    }
    

    然后我的查询看起来像 -

    c.Find(bson.M{"brandId": body.BrandID, "category": body.Category, "$and": AndQuery})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多