Stennie 的解决方案要求您确切知道要从您正在查询的集合中的每个匹配项中返回哪些属性。情况并非总是如此。
我们必须在我们正在编写的 Groovy on Grails 应用程序中解决这个问题。
我们编写了一个这样的方法来处理“按 X 查找”请求:
private List<DBObject> findDistinctPages(Map by) {
def command =
new GroupCommand(
(DBCollection) db.pages,
new BasicDBObject(['url': 1]),
new BasicDBObject(by),
new BasicDBObject([:]),
'function ( current, result ) { for(i in current) { result[i] = current[i] } }',
''
)
db.pages.group(command).sort { it.title }
}
然后在我们的代码中调用它,如下所示:
def pages = findDistinctPages([$or: [[type: 'channel'], [type: 'main']]])
这通过将初始查询的结果传递给 GroupCommand 末尾的 javascript 函数来实现。Mongo 仅返回您在初始查询中指定的属性,没有其他任何内容,因此您必须第二次迭代结果,并使用来自 mongo 的其余数据填充它们。