Skip to content
Advertisement

How to group by sub documents and get unique value of value field?

This is my database collection:

JavaScript

Now I want to send the data of only the attribute where isVariation is not 0. Also I want to send the variant values of each attribute where isComplete =1. Hence the result should look like this

JavaScript

The above result does not have value of 2.5 inch as the isComplete is 0 for this document. Can anyone help me with the query

Advertisement

Answer

  • $match isComplete is 1
  • $project to show required fields
  • $unwind deconstruct attributeSet array
  • $match attributeSet.isVariation is not 0
  • $group by attributeSet.id and get first name and get unique value using $addToSet
JavaScript

Playground

The $project stage is not required in your query, i have added because this will optimize your query performance.

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