小编典典

使用golang在具有多个条件的mongo查询中发布

go

我有以下文件-

{ 
    "_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执行搜索时,理想情况下,我会传递类似于请求properties正文中的数组POST-

{ 
    "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"`
}

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

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

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

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

应该如何处理?


阅读 430

收藏
2020-07-02

共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})
2020-07-02