MapReduce view gives different results for map vs. reduce

I have a map function that filters out documents based on a date range and it works as expected. If I run a similar N1QL query I get the same results as the view map. However, when I reduce via CB’s internal _stats function, I get a HIGHER record count than without the reduce.

Map Function (w/o reduce):

function (doc, meta) {
    // These are Magento statuses
    var statuses = ['complete', 'pending', 'processing'];
    if (doc.type == 'mage-sales-order') {
        var soDate = new Date(doc.salesorder.MageSalesOrder.created_at);
        var rolling = new Date();
        rolling.setDate(rolling.getDate() - 6);
        rolling.setHours(0, 0, 0, 0);
        if (statuses.indexOf(doc.salesorder.MageSalesOrder.status) > -1 && soDate >= rolling) {
            var total = Number(doc.salesorder.MageSalesOrder.grand_total);
            if (total != "NaN" && total > 0) {
                emit(meta.id, total);
            }
        }
    }
}

Outputs:

{"total_rows":7,"rows":[...]}

Now when I reduce with “_stats”

{
  "sum": 2150.48,
  "count": 9,
  "min": 159.2,
  "max": 465.45,
  "sumsqr": 582230.4772000001
}

Notice the record count is now 9 and the “sum” value is incorrect, too (summing the 7 results from the pure map function yields a lower amount, as expected).

What’s happening here?

I was not able to resolve this so I removed the _stats reduce function from my view and am handling aggregation and calculations in my app instead.

Hi - would it be possible to provide the 7 doc.salesorder.MageSalesOrder.grand_total values?

Hi Siri, thanks for asking. Since this is a rolling report, I’ll just post today’s values:

Without Reduce my Map returns 8 rows totaling 1,960.85:

	{"total_rows":8,"rows":[
			{"id":"ugobags-uos-mage-sales-order-000000284","key":"ugobags-uos-mage-sales-order-000000284","value":214.83},
			{"id":"ugobags-uos-mage-sales-order-000000285","key":"ugobags-uos-mage-sales-order-000000285","value":211.65},
			{"id":"ugobags-uos-mage-sales-order-000000286","key":"ugobags-uos-mage-sales-order-000000286","value":169.15},
			{"id":"ugobags-uos-mage-sales-order-000000287","key":"ugobags-uos-mage-sales-order-000000287","value":159.87},
			{"id":"ugobags-uos-mage-sales-order-000000288","key":"ugobags-uos-mage-sales-order-000000288","value":549.95},
			{"id":"ugobags-uos-mage-sales-order-000000289","key":"ugobags-uos-mage-sales-order-000000289","value":137.4},
			{"id":"ugobags-uos-mage-sales-order-100000430","key":"ugobags-uos-mage-sales-order-100000430","value":259},
			{"id":"ugobags-uos-mage-sales-order-100000431","key":"ugobags-uos-mage-sales-order-100000431","value":259}
			]
	}

With the _stats Reduce function I get the following:

{
	"sum": 1275.37,
	"count": 5,
	"min": 137.4,
	"max": 549.95,
	"sumsqr": 442574.9019000001
}

Hopefully this at least clarifies the discrepancy.