Skip to content
Advertisement

How to return the variant values of each product if that product is a variant?

I have a database in MongoDB like this

JavaScript

Now I want to return data where 500 GB has been in productId 1 and 3 The response should be like this:

JavaScript

I have the possible values that I store in another collection for variantPossible values. The values that i am storing are like this:

JavaScript

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.

Advertisement

Answer

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:

JavaScript

See this simplifed example on mongoplayground: https://mongoplayground.net/p/VASadZnDedc

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement