title: Is there a cleaner way to do this Group Query in MongoDB from Groovy?
body: <p>I'm working on learning MongoDB. Language of choice for the current run at it is Groovy.</p>
  
  <p>Working on Group Queries by trying to answer the question of which pet is the most needy one.</p>
  
  <p>Below is my first attempt and it's <em>awful</em>. Any help cleaning this up (or simply confirming that there isn't a cleaner way to do it) would be much appreciated.</p>
  
  <p>Thanks in advance!</p>
  
  <pre><code>package mongo.pets
  
  import com.gmongo.GMongo
  import com.mongodb.BasicDBObject
  import com.mongodb.DBObject
  
  class StatsController {
  
    def dbPets = new GMongo().getDB('needsHotel').getCollection('pets')
  
    //FIXME OMG THIS IS AWFUL!!!
    def index = {
      def petsNeed = 'a walk'
  
      def reduce = 'function(doc, aggregator) { aggregator.needsCount += doc.needs.length }'
      def key = new BasicDBObject()
      key.put("name", true)
      def initial = new BasicDBObject()
      initial.put ("needsCount", 0)
  
      def maxNeeds = 0
      def needyPets = []
      dbPets.group(key, new BasicDBObject(), initial, reduce).each {
        if (maxNeeds &lt; it['needsCount']) {
          maxNeeds = it['needsCount']
          needyPets = []
          needyPets += it['name']
        } else if (maxNeeds == it['needsCount']) {
          needyPets += it['name']
        }
      }
  
      def needyPet = needyPets
  
      [petsNeedingCount: dbPets.find([needs: petsNeed]).count(), petsNeed: petsNeed, mostNeedyPet: needyPet]
    }
  
  }
  </code></pre>