Applying $reduce to an array of objects during $addFields

I have a collection of documents that has a field which is an array of objects - call the objects flights. Within each object, there is a field - let’s call it checkField. I am trying to use $addFields to create a field which represents the number of flights whose checkField value matches a condition (in this case, I’m attempting to match a few strings with regex).

My current solution entails applying $reduce to the array, and conditionally checking whether checkField matches the condition. The logic looks something like this:
{ $reduce: { input: “$flightsArray”, initialValue: 0, in: { count: { $add : ["$$value.sum", { $cond: { if: { $or: [{ “$$this.checkField”: { $regex: /.STRING1./ } }, { “$$this.checkField”: { $regex: /.STRING2./ } }] }, then: 1, else: 0 } }] } } } }

Here is an image to help with that in expression:

The problem that I’m facing is an error message: "Unrecognized expression ‘$$this.checkField’ "

By my understanding, $$this is the variable that refers to the element being processed. In my case, the element being processed is an object with a field named checkField.

So I’m not sure if it’s a scoping problem, or I’m misusing this.

Also, I acknowledge that this whole set-up is wonky. Perhaps you can tell which problem I’m working on (I obviously tried to be vague in accordance with the “Please do not post potential answers in the forums” notice). My thinking was that I had two options: operate on the array and return a count, or $unwind at the array and then $group with accumulators. I picked to operate on the array because of the seeming explosion of records which would have occurred after an $unwind.



A couple of things to consider/note:

  1. $regex is a query operator and not an aggregation pipeline operator so it won’t work in the in section. See the documentation for the three equivalents that are available in 4.2+.
  2. Consider filtering out the sub documents in the input section beforehand
  3. Is there an alternative to the regex pattern? E.g. splitting and substringing?