title: MongoDB: any way to use a user defined function in an aggregation?
body: <p>I have the following records:</p>
  
  <pre><code>{ "_id" : ObjectId("55889370ba09474fd178d8b8"), "url" : "http://stackoverflow.com/questions/ask"} 
  { "_id" : ObjectId("55889370ba09474fd178d8b4"), "url" : "http://stackoverflow.com"}
  { "_id" : ObjectId("55889370ba09474fd178d8b2"), "url" : "http://espn.com"}
  </code></pre>
  
  <p>And I want to do an aggregation to get the count of each site by their root. Basically I want both of the first two records to fall under the same group (they have the same root).</p>
  
  <p>I created an user defined function to transform the url into its root. My idea was to use the user defined function to first project the records (changing the url field) and then grouping by the url. The problem is that apparently user defined functions can't be used in aggregations. They can be used in where clauses in a projection but projections with where clauses can't be used in an aggregation.</p>
  
  <p>Is there any way I can the aggregation I need?</p>
  
  <p>EDIT:</p>
  
  <p>Maybe to make the example more illustrative I should add that if I for example wanted to group by the root website and count them I would get something like:</p>
  
  <pre><code>{ "_id" : "http://stackoverflow.com", "count" : 2}
  { "_id" : "http://espn.com", "count" : 1}
  </code></pre>