1

In the group stage I want to create a new array of colors, the colors are objects of two fields (name, value), the resulted array must contain colors with unique color names.

{
      $group: {
          _id: null,
          sizes: { $addToSet: '$combinations.size' },
          colors: { $push: '$combinations.color' },
          brands: {
              $addToSet: { $cond: [{ $eq: ['$brand', ''] }, '$$REMOVE', '$brand'] },
          },
          topPrice: { $max: `$price.${req.query.reg || 'aud'}` },
          bottomPrice: { $min: `$price.${req.query.reg || 'aud'}` },
      },
},

the combination.color field is an object is there a way to make a set that will add new colors if they had a unique color name?

Noel
  • 10,152
  • 30
  • 45
  • 67

1 Answers1

0

You may have to remove the duplicates separately, after the grouping.

Using $reduce

db.collection.aggregate([
  {
    $group: {
      _id: null,
      colors: {
        $addToSet: "$color"
      }
    }
  },
  {
    $set: {                                          //Add another stage to set the colors array
      "colors": {                                    //input will be the existing colors array
        $reduce: {                                   //use reduce operator to iterate through each array element
          input: "$colors",                          
          initialValue: [],                          //start with an empty error. This will be referenced as $$value
          in: {
            $cond: [                                   //for each element in colors array, check if name exists in $$value
              {
                $in: ["$$this.name", "$$value.name"]
              },
              {
                $concatArrays: ["$$value"]             //if exists, do nothing
              },
              {
                $concatArrays: ["$$value", ["$$this"]] //if not, concat the array element to $$value
              }
            ]
          }
        }
      }
    }
  }
])

Demo

Noel
  • 10,152
  • 30
  • 45
  • 67