title: Streaming the result of an aggregate operation using spring-data-mongodb
body: <p>I am using spring-data-mongodb and I want to use a cursor for an aggregate operation.</p>
  
  <p><em>MongoTemplate.stream()</em> gets a Query, so I tried creating the Aggregation instance, convert it to a <em>DbObject</em> using <em>Aggregation.toDbObject()</em>, created  a <em>BasicQuery</em> using the <em>DbObject</em> and then invoke the <em>stream()</em> method.<br>
  This returns an empty cursor.</p>
  
  <p>Debugging the spring-data-mongodb code shows that <em>MongoTemplate.stream()</em> uses the <em>FindOperation</em>, which makes me thinkspring-data-mongodb does not support streaming an aggregation operation.<br>
  Has anyone been able to stream the results of an aggregate query using spring-data-mongodb?</p>
  
  <p>For the record, I can do it using the Java mongodb driver, but I prefer using spring-data.</p>
  
  <p><strong>EDIT</strong> Nov 10th - adding sample code:</p>
  
  <pre><code>    MatchOperation match = Aggregation.match(Criteria.where("type").ne("AType"));
      GroupOperation group = Aggregation.group("name", "type");
      group = group.push("color").as("colors");
      group = group.push("size").as("sizes");
      TypedAggregation&lt;MyClass&gt; agg = Aggregation.newAggregation(MyClass.class, Arrays.asList(match, group));
  
      MongoConverter converter = mongoTemplate.getConverter();
      MappingContext&lt;? extends MongoPersistentEntity&lt;?&gt;, MongoPersistentProperty&gt; mappingContext = converter.getMappingContext();
      QueryMapper queryMapper = new QueryMapper(converter);
      AggregationOperationContext context = new TypeBasedAggregationOperationContext(MyClass.class, mappingContext, queryMapper);
      // create a BasicQuery to be used in the stream() method by converting the Aggregation to a DbObject
      BasicQuery query = new BasicQuery(agg.toDbObject("myClass", context));
  
      // spring-mongo attributes the stream() method to find() operationsm not to aggregate() operations so the stream returns an empty cursor
      CloseableIterator&lt;MyClass&gt; iter = mongoTemplate.stream(query, MyClass.class);
  
      // this is an empty cursor
      while(iter.hasNext()) {
          System.out.println(iter.next().getName());
      }
  </code></pre>
  
  <p>The following code, not using the stream() method, returns the expected non-empty result of the aggregation:</p>
  
  <pre><code>    AggregationResults&lt;HashMap&gt; result = mongoTemplate.aggregate(agg, "myClass", HashMap.class);
  </code></pre>