How To Return The Variant Values Of Each Product If That Product Is A Variant?
I have a database in MongoDB like this {'productId' : 1, 'isVariant': 1, 'variantId' : 1, 'attributeSet' : [ { 'name' : 'Capacity', 'value' : '500
Solution 1:
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.
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"
}
}
])
See this simplifed example on mongoplayground: https://mongoplayground.net/p/VASadZnDedc
Post a Comment for "How To Return The Variant Values Of Each Product If That Product Is A Variant?"