title: Nodejs + Mongodb: find data after aggregation
body: <p>I'm a new to Nodejs and MongoDB.<br>
  Here is a sample of my dataset:</p>
  
  <pre><code>{ 
    'name': ABC,
    'age':24,
    'gender':male,
    ...
  }
  </code></pre>
  
  <p>Generally speaking, what I want to do is to aggregate data before using them to find different data clusters.<br>
  To be specific, I want to know how many people there are at different ages. Then, to find people(documents) at each age and store them.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>MongoClient.connect(url, function(err, db) {
      if(err) { 
          console.log('Unable to connect to the mongoDB server. Error:', err); 
      } else { 
          db.collection('test').aggregate(
          [
            { $group: { _id: "$age" , total: { $sum: 1 } } },
            { $sort: { total: -1 } } 
          ]).toArray(function(err, result) {
              assert.equal(err, null);
              age = [];
              for(var i in result) {
                  age.push(result[i]['_id'])
              };
              ageNodes = {};
              for(var i in age) {
                   nodes = [];
                   var cursor = db.collection('test').find({'age':age[i]});
                   // query based on aggregated data
                   cursor.each(function(err,doc){
                      if(doc!=null){
                          nodes.push(doc);
                      } else {
                          console.log(age[i]);
                          ageNodes[age[i]] = nodes;
                      }
                  })
              }
              res.json(ageNodes);
          });
      };
  });
  </code></pre>
  
  <p>My expected JSON format:</p>
  
  <pre><code>{
    age:[different documents]
  }
  </code></pre>
  
  <p>example:</p>
  
  <pre><code>{
    20:[{name:A,gender:male,...},{},...],
    30:[{name:B,gender:male,...},{},...],
    ...
  }
  </code></pre>
  
  <p>However, what I got was an empty result, so I think maybe it was caused by the for loop.<br>
  I have no idea how to handle the asynchronous callback.</p>