title: How to use Aggregate in mongoose
body: <p>How do I define the following MongoDB aggregate query in mongoose:</p>
  
  <pre><code>db.contacts.aggregate([{$group: { "_id": { code: "$Code", name: "$Name" } } }])
  </code></pre>
  
  <p>The objective of the query is to pull a list of distinct codes and names.</p>
  
  <p>My current model code is: </p>
  
  <pre><code>'use strict';
  
  var mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      ObjectId = Schema.ObjectId;
  
  var fields = {
      Code: { type: String },
      Name: { type: String }
  };
  
  var contactSchema = new Schema(fields);
  
  module.exports = mongoose.model('Contacts', contactSchema);
  </code></pre>
  
  <p>Router looks like this:</p>
  
  <pre><code>api.contacts = function (req, res) {
  Contacts.find({ AgencyTranslation: /^BROADCASTING/ }, function(err, contacts) {
    if (err) {
      res.json(500, err);
    } else {    
      res.json({contacts: contacts});
    }
  });
  </code></pre>
  
  <p>I tried various variations, also looked up the sample code at: <a href="http://mongoosejs.com/docs/api.html#aggregate_Aggregate" rel="noreferrer">mongoose API docs</a>, but I cannot seem to get it working.</p>
  
  <p>(Note: the above query does work in the MongoDB console.)</p>