title: Aggregation sum in Spring Data MongoDB
body: <p>I have MongoDB Page and Post collections. Each page document has field postIds which is array of post Ids (String objects). I want to use aggregation to count number of posts (=number of elements in array postIds) for each page. I wrote Mongo Shell aggregation function which returns exactly what I want:</p>
  
  <pre><code>db.page.aggregate([
      {$unwind : '$postIds'},
      {$group : {_id: '$_id', 'sum': { $sum: 1}}}
  ])
  </code></pre>
  
  <p>and it returns this result:</p>
  
  <pre><code>{ "_id" : "3", "sum" : 3 }
  { "_id" : "2", "sum" : 3 }
  </code></pre>
  
  <p>This means that page with id 3 has 3 posts, and page with id 2 has 3 posts as well, which is correct.</p>
  
  <p>Now I wanted to write same using Spring MongoDB Aggregation, and wrote this simple JUnit test:</p>
  
  <pre><code>    /**
       * Test page posts count
       */
      @Test
      public void testPagePostsCount() throws Exception{
          MongoTemplate template = repository.getMongoTemplate();
          Page page = new Page();
          page.setPageId("2210");
          page.setUserId("azec");
          List&lt;String&gt; postList = new ArrayList&lt;String&gt;();
          postList.add("53eb1a560efbe048c7ea698d");
          postList.add("53eb1a6b0efbe048c7ea698e");
          page.setPostIds(postList);
          template.save(page);
  
          Aggregation agg = newAggregation(
              match(Criteria.where("pageId").is("2210")),
              unwind("postIds"),
              group("_id").sum("1").as("sum")
              //project("$sum").and("pageId").previousOperation()
          );
  
          AggregationResults&lt;PostCount&gt; results = template.aggregate(agg, "page", PostCount.class);
          List&lt;PostCount&gt; postCount = results.getMappedResults();
  
          System.out.println("Done!");
      }
  </code></pre>
  
  <p>However, this aggregation query returns this native Mongo query:</p>
  
  <p>2014-08-13 20:06:07,949 DEBUG [org.springframework.data.mongodb.core.MongoTemplate] - Executing aggregation: </p>
  
  <pre><code>{
     "aggregate":"page",
     "pipeline":[
        {
           "$match":{
              "pageId":"2210"
           }
        },
        {
           "$unwind":"$postIds"
        },
        {
           "$group":{
              "_id":"$_id",
              "sum":{
                 "$sum":"$1"
              }
           }
        }
     ]
  }
  </code></pre>
  
  <p>Questions:
  1. As you can see, the difference is with the $sum value of $1. I need to pass there number 1 instead of $1, but I am not sure how. 
  2. Do I need project operation here?</p>
  
  <p>Thanks</p>