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

Issue in mongo query with multiple conditions by using golang

我有一个文档如下-

{ 
    "_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})