MongoDB Exception: aggregation result exceeds maximum document size (16MB)

MongoDB aggregation result exceeds maximum document size (16MB)

{
“errmsg” : “exception: aggregation result exceeds maximum document size (16MB)”,
“code” : 16389,
“ok” : 0
}

Cause:

  • You are using MongoDB version <=2.4
  • You are using MongoDB version >=2.6 but are using a mongo shell 2.4 or a PHP/C/Java/Ruby driver to run aggregate() without specifying the output as “cursor”

Solution for 2.4: Limit the output using $skip and $limit to fit the 16MB limit

Solution for 2.6:

Java driver: Use option:

.newAggregationOptions().outputMode(
AggregationOptions.OutputMode.CURSOR).build()

PHP driver:

public MongoCommandCursor MongoCollection::aggregateCursor ( array $command [, array $options ] )