title: MongoDB Querying: Order & Export Results
body: <p>I have this MongoDB group-by query which works great from the Mongo console:</p>
  
  <pre><code>db.accounts.group(
     { cond: { "created_at" : { $gte: ISODate("2012-08-12T00:00:00Z") }}
     , key: {member_id: true}
     , initial: {count: 0, failed: 0, succeeded: 0}
     , reduce: function(doc, out) { 
          out.count++; 
          if (!doc.success)
              out.failed++
          else
              out.succeeded++
      }
     });
  </code></pre>
  
  <p><strong>My three questions:</strong></p>
  
  <ul>
  <li>Is there an easier way of generating this timestamp: ISODate("2012-08-12T00:00:00Z")? Can I use a date function to generate this timestamp? If so, how?</li>
  <li>How can I sort (asc/desc) the returned results by the grouped fields: "failed" or "succeeded"?</li>
  <li>Finally, how would I export the output to a flat file?</li>
  </ul>
  
  <p><strong>Update</strong></p>
  
  <p>For #3, I was basically looking for this:</p>
  
  <pre><code>mongo my_db --eval 'some_var=X;' --quiet my_script.js &gt;&gt; output.txt
  </code></pre>
  
  <p>Where my_db is the database I'm using, some_var is a variable I'm passing to my_script.js which contains my group-by query. output.txt is obviously where the output is written.</p>