Java 在Groovy的MongoDB中,有没有更干净的方法来执行此组查询?

Java 在Groovy的MongoDB中,有没有更干净的方法来执行此组查询?,java,groovy,mongodb,Java,Groovy,Mongodb,我正在学习MongoDB。当前运行的首选语言是Groovy 通过尝试回答哪只宠物是最需要的宠物的问题来进行小组查询 下面是我的第一次尝试,太可怕了。如果您能帮我清理一下,或者只是确认没有更干净的方法,我们将不胜感激 提前谢谢 package mongo.pets import com.gmongo.GMongo import com.mongodb.BasicDBObject import com.mongodb.DBObject class StatsController { def

我正在学习MongoDB。当前运行的首选语言是Groovy

通过尝试回答哪只宠物是最需要的宠物的问题来进行小组查询

下面是我的第一次尝试,太可怕了。如果您能帮我清理一下,或者只是确认没有更干净的方法,我们将不胜感激

提前谢谢

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 < 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]
  }

}
应该可以将整个方法更改为这个,但我没有MongoDB来测试它

def index = {
  def petsNeed = 'a walk'

  def reduce = 'function(doc, aggregator) { aggregator.needsCount += doc.needs.length }'

  def key     = [ name: true    ] as BasicDBObject
  def initial = [ needsCount: 0 ] as BasicDBObject

  def allPets = dbPets.group( key, new BasicDBObject(), initial, reduce )
  def maxNeeds = allPets*.needsCount.collect { it as Integer }.max()
  def needyPet = allPets.findAll { maxNeeds == it.needsCount as Integer }.name

  [petsNeedingCount: dbPets.find([needs: petsNeed]).count(), petsNeed: petsNeed, mostNeedyPet: needyPet]
}

这有什么可怕的地方?性能?实现。太吵了。新的BasicDBObject.put甚至会使它变得更好,因为我现在正在查看它。此外,获取组查询的最大值将是一个内存操作。如果这是数百万件物品呢?我希望这一切都发生在DB级别,这确实是一种更为常规的代码编写方式。有一个小错误。为了匹配原始代码段的行为,您需要额外的一行代码。needyPet=needyPet.collect{it['name']}只在序列中包含需要的宠物的名字。尽管如此,这仍然是一种可怕的方式,你不觉得吗?你完全在记忆中?我能够完全在DB端使用javascript在控制台上完成这项工作,并提供排序和限制等功能。我真正想要的是对groovy代码中的功能进行排序和限制是的,我同意这一切都在记忆中所以可能会有问题。。。我希望你在发布问题时说这是你的问题。。。为什么不通过api在命令行上执行查询呢?这是什么意思?通过…执行官?这似乎很有意思。有没有通过Java执行直接命令的有效方法?