Returning an array of strings if the value of the key is true

In the middle of $facet aggregation, I am having an array of objects, each object looks like this:

{
  _id: ObjectId,
  colors: {
    blue: true,
    red: true,
    green: true,
    yellow: false,
  }
  ...restOfData
}

while I’m going through all records, I want to access the colors key and make it an array of strings equal to the value that is true like this: [ 'Blue', 'Green', 'Blue' ].

End result should look like this:

{
  _id: ObjectId,
  colors:  [ 'Blue', 'Green', 'Blue' ],
  ...restOfData
}

aggregation code:

$facet:{
  products_facet: [
    {
      $group: {
        _id: null,
        products: {
          $push: "$$ROOT",
         *This is when I want to manipulate colors"
        },
      },
    },
 ]
}

Hi @Aviv_azulay

To transform the colors field into an array of strings, you can use the $objectToArray and $filter stages in the aggregation pipeline.

Here is an example of how you can modify your aggregation pipeline to achieve the desired result:

$facet: {
  products_facet: [
    {
      $group: {
        _id: null,
        products: {
          $push: {
            $mergeObjects: [
              "$$ROOT",
              {
                colors: {
                  $filter: {
                    input: {
                      $objectToArray: "$colors"
                    },
                    as: "color",
                    cond: {
                      $eq: [ "$$color.v", true ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  ]
}

The $objectToArray stage converts the colors field from an object to an array of key-value pairs. The $filter stage then filters this array to only include the key-value pairs where the value is true. Finally, the $mergeObjects stage merges the resulting array of key-value pairs back into the original document, replacing the colors field with the desired array of strings.

This will result in the colors field being transformed into an array of strings, as shown in the example in your question.

1 Like