如果该产品是变体,如何返回每个产品的变体值? [英] How to return the variant values of each product if that product is a variant?
问题描述
我在MongoDB中有这样的数据库
I have a database in MongoDB like this
{"productId" : 1,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "500 GB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
},
{"productId" : 2,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
},
{"productId" : 3,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "500 GB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "2.5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
},
{"productId" : 4,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "2.5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
}
现在我要返回 productId
1和3中500 GB的数据响应应该是这样的:
Now I want to return data where 500 GB has been in productId
1 and 3
The response should be like this:
variantValues : [{
attributeValue : "500 GB",
data : [
{productId : 1},
{productId : 3}
]},
{
attributeValue : "1 TB",
data : [
{productId : 2},
{productId : 4}
]},
{
attributeValue : "2.5 inch",
data : [
{productId : 3},
{productId : 4}
]},
{
attributeValue : "5 inch",
data : [
{productId : 1},
{productId : 2}
]}]
我有可能存储在另一个集合中的 variantPossible
值.我存储的值是这样的:
I have the possible values that I store in another collection for variantPossible
values. The values that i am storing are like this:
"VariantValues" : {
"3" : [
"500 GB",
"1 TB"
],
"4" : [
"2.5 inch",
"5 inch"
]
},
如果每个产品都是上述格式的变体,我想返回每个产品的变体值.谁能帮我这个忙.
I want to return the variant values of each product if that product is a variant with the above format. can anyone help me with this.
推荐答案
您应该能够在聚合管道中使用 $ unwind
和 $ group
来实现这一目标.首先,将每个属性拼合为一个文档,然后将其按属性值分组.
You should be able to achieve this using $unwind
and $group
in your aggregation pipeline. This first flattens each attribute into a single document and on those you can group by the attribute value.
最后,您可以使用 $ project
获得 attributeValue
的所需名称:
Finally, you can use $project
to get the desired name for attributeValue
:
db.collection.aggregate([
{
$unwind: "$attributeSet"
},
{
$group: {
_id: "$attributeSet.value",
data: {
"$addToSet": {
productId: "$productId"
}
}
}
},
{
"$project": {
_id: 0,
data: 1,
attributeValue: "$_id"
}
}
])
在mongoplayground上查看以下简化示例: https://mongoplayground.net/p/VASadZnDedc
See this simplifed example on mongoplayground: https://mongoplayground.net/p/VASadZnDedc
这篇关于如果该产品是变体,如何返回每个产品的变体值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!