This is in the documentation for MapReduce from 4.2 to 6.0:
MongoDB will not call the reduce function for a key that has only a single value. The values argument is an array whose elements are the value objects that are "mapped" to the key.
However, from 4.4 onwards, the reduce function will be called regardless of how many values are associated with a given key. PM-766 added a new execution engine for MapReduce commands based on the Aggregation Framework that is active in 4.4 and above.
If the implementation is changed, then two possible fixes are:
- AccumulatorJsReduce::getValue() can be modified to not call into the JS reduce function if the length the _values vector is exactly 1. Instead, it will just return that value to the caller. This fix has the benefit of not adding any logic to the generated MQL.
- The translateReduce() function can be modified to only call the internal JsReduce accumulator if the $emits array has a length larger than 1, and otherwise, just return the document inside $emits.