title: How do I write this Mongo aggregation query in Spring?
body: <p>I've got an aggregation query in MongoDB that works when I run it directly in the shell. Here's the shell query:</p>
  
  <pre><code>db.MyCollection.aggregate([
      {$match: {_id: {$in: ['A', 'B', 'C']}}},
      {$project: {"versions": "$nested.field.version"}},
      {$unwind: "$versions"},
      {$group: {_id: "$_id", "maxVersion": {$max: "$versions"}}}
  ])
  </code></pre>
  
  <p>So as you can see, this does the following:</p>
  
  <ol>
  <li>Matches only certain documents with specified IDs</li>
  <li>Projects a nested field down to a base-level field (and effectively filters out all other fields from the pipeline, but still retaining the IDs)</li>
  <li>Unwinds the array elements of the $versions field that we projected into individual documents in the pipeline</li>
  <li>Finds the max value of those $versions per ID</li>
  </ol>
  
  <p>Like I said, that query above already works. My question is how to translate that into Spring MongoDB syntax. Here's my first attempt, which does <strong>not</strong> work:</p>
  
  <pre><code>Aggregation aggregation = newAggregation(
      match(Criteria.where("_id").in(listOfIds))
      ,project().and("versions").nested(bind("versions", "nested.field.version"))
      ,unwind("versions")
      ,group("_id").max("versions").as("maxVersion")
  );
  </code></pre>
  
  <p>When I try to run the code in debug mode, I can see that I actually get an IllegalArgumentException on newAggregation saying it cannot evaluate. If I comment out the line with the $group clause, then I can see this toString() representation of aggregation variable, which reveals a problem with the $project clause:</p>
  
  <pre><code>{
    "aggregate" : "__collection__" ,
    "pipeline" : [
      { "$match" : { "_id" : { "$in" : [ "A" , "B" , "C"]}}} ,
      { "$project" : { "versions" : { "versions" : "$nested.field.version"}}} ,
      { "$unwind" : "$versions"}
    ]
  }
  </code></pre>
  
  <p>Clearly this doesn't match up with what I was intending so I'm not getting the syntax correct. But TBH I don't find the Spring MongoOps syntax very intuitive, and their documentation isn't great either.</p>
  
  <p>I don't see any way to call that <code>nested()</code> method without first including the call to <code>and()</code>. I think that's the main problem since it's doubling up the nesting there. Are there any Spring MongoOps heroes here who can help me write the equivalent Java code properly?</p>
  
  <p><strong>EDIT:</strong> Here's a snapshot of the collection I'm using: <a href="https://i.stack.imgur.com/svp7A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/svp7A.png" alt="robomongo display"></a></p>