$reduce.in Unrecognized expression '$addToSet'

I am trying to use $reduce to

  1. input an array of documents
  2. return a set of values from those documents – for documents that match a criteria

I am having no issues with the matching, so I will leave that out of the description. My problem is with attempting to use $addToSet within $reduce to gather unique values from the input.

If the target area of the input document is as follows, I want to end up with a set in the base document with element airlines:[“Air Europa”]
routes:[
{
“_id” : ObjectId(“56e9b39c732b6122f878e729”),
“airline” : {
“id” : 90,
“name” : “Air Europa”
}
},
{
“_id” : ObjectId(“56e9b39c732b6122f878e749”),
“airline” : {
“id” : 90,
“name” : “Air Europa”
}
}
]

I am attempting to implement the reduce using

{$project:{
  _id:0,
  airlines:{
    $reduce:{
      input:"$routes",
      initialValue: [],
      in:{$addToSet:"$$this.airline.name"}
      }
  }

However, I get the error Unrecognized expression ‘$addToSet’.

If I change the in clause to something bogus like the following – it syntactically works and functionally appears to do what I have asked.

  initialValue: 0,
  in:{$add:["$$value","$$this.airline.id"]}

If I attempt to do something similar with $addToSet, I get the same, original error (“Unrecognized expression ‘$addToSet’”)

  initialValue: [],
  in:{$addToSet:["$$value","$$this.airline.id"]}

Predictably, I get the same error with most of the other accumulator functions.

How can I use $reduce to return a set of unique values from the input array?

thanks!

@ ejavaguy

As the documentation on $addToSet here says, $addToSet is only available in the $group stage.

Sure enough. You found the reason why $addToSet was not working for me. Thanks.

My previous solution used $addToSet in the $group stage that followed an $unwind. However, I was trying to apply the anti-fanout discussed in the $project+$reduce lecture. Is there another way to accomplish what I am looking for and stick to the concepts discussed with $reduce?

It seems like I have the ability to count occurrences and calculate sumes (like in the example) but not remember the occurrence values or unique values – without going back to $unwind and $group.