【发布时间】:2011-02-02 23:18:57
【问题描述】:
我正在学习 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]
}
}
【问题讨论】:
-
这有什么可怕的——性能?
-
实施。噪音太大了new BasicDBObject().put 现在我正在查看它甚至会变得更好。此外,获取组查询的最大值将是内存操作。如果这是数百万个项目怎么办?我希望这一切都发生在数据库级别。