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

Issue in mongo query with multiple conditions by using golang

本文关键字:mongo 查询 条件 golang 使用      更新时间:2023-09-26

我有一个文档如下-

{ 
    "_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数组的大小作为输入,但无法得到正确的方法!

这应该如何处理?

我能够通过单独构建$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})