I have a record structured like this -
{
"_id" : "580eef0e4dcc220df897a9cb",
"brandId" : 15,
"category" : "air_conditioner",
"properties" : [
{
"propertyName" : "A123",
"propertyValue" : "A123 678"
},
{
"propertyName" : "B123",
"propertyValue" : "B123 678"
},
{
"propertyName" : "C123",
"propertyValue" : "C123 678"
}
]
}
When using my API to search,
I would typically send an array similar to properties
in the body of my POST
request -
{
"brandId" : 15,
"category" : "air_conditioner",
"properties" : [
{
"propertyName" : "A123",
"propertyValue" : "A123 678"
},
{
"propertyName" : "B123",
"propertyValue" : "B123 678"
},
{
"propertyName" : "C123",
"propertyValue" : "C123 678"
}
]
}
To handle this data on my end, I've set up a structure for decoding it -
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"`
}
I also want to execute a mongodb $and
operation on the various properties
, and only return documents that match all criteria.
My issue lies in the fact that the number of elements within the properties
array can vary.
I need to be able to query with just
{
"brandId" : 15,
"category" : "air_conditioner",
"properties" : [
{
"propertyName" : "A123",
"propertyValue" : "A123 678"
}
]
}
and receive multiple matching documents (not just one).
I attempted to create a dynamically sized bson.M
variable using a loop based on the size of the incoming properties
array but struggled to find the correct approach!
What is the best way to tackle this problem?