title: MongoDB-Java: How to make $geoNear to first do query, then distance?
body: <p>I'm trying to query and sort documents as followed:</p>
  
  <ul>
  <li>Query only for documents older than SOMETIME.</li>
  <li>Within range of AROUNDME_RANGE_RADIUS_IN_RADIANS.</li>
  <li>Get distance for each document.</li>
  <li>Sort them by time. New to Old. </li>
  <li>Overall it should return up to 20 results.</li>
  </ul>
  
  <p>But it seems that since $geoNear is by default limited to 100 results, I get unexpected results.
  <br/>I see $geoNear working in the following order:</p>
  
  <ol>
  <li>Gets docs from the entire collection, by distance.</li>
  <li>And only then executes the given Query.</li>
  </ol>
  
  <p>Is there a way to reverse the order? 
  <br/>MongoDB v2.6.5
  <br/>Java Driver v2.10.1
  <br/><br/>Thank you.
  <br/><br/><br/>
  Example document in my collection:</p>
  
  <pre><code>{
      "timestamp" : ISODate("2014-12-27T06:52:17.949Z"),
      "text" : "hello",
      "loc" : [ 
          34.76701564815013, 
          32.05852053407342
      ]
  }
  </code></pre>
  
  <p>I'm using aggregate since from what I understood it's the only way to sort by "timestamp" and get the distance.</p>
  
  <pre><code>BasicDBObject query = new BasicDBObject("timestamp", new BasicDBObject("$lt", SOMETIME));
  
              // aggregate: geoNear
              double[] currentLoc = new double[] {
                      Double.parseDouble(myLon), 
                      Double.parseDouble(myLat)
              };
              DBObject geoNearFields = new BasicDBObject();
              geoNearFields.put("near", currentLoc);
              geoNearFields.put("distanceField", "dis");
              geoNearFields.put("maxDistance", AROUNDME_RANGE_RADIUS_IN_RADIANS));
              geoNearFields.put("query", query);
              //geoNearFields.put("num", 5000);  // FIXME: a temp solution I would really like to avoid
              DBObject geoNear = new BasicDBObject("$geoNear", geoNearFields);
  
              // aggregate: sort by timestamp
              DBObject sortFields = new BasicDBObject("timestamp", -1);
              DBObject sort = new BasicDBObject("$sort", sortFields);
  
              // aggregate: limit
              DBObject limit = new BasicDBObject("$limit", 20);
  
              AggregationOutput output = col.aggregate(geoNear, sort, limit);
  </code></pre>