【发布时间】:2014-12-03 16:06:01
【问题描述】:
如果masterID 不存在,我有一组对象需要按masterID 或id 分组。在具有相同masterID 的一组对象中,我需要找到具有最高pos 属性($max: "$pos")的对象。但是,我很难获得最大化pos 的完整对象,似乎通过聚合我只能获得pos 属性,而不是整个对象。这是我使用的示例聚合,缺少$ifNull 的masterID:
> db.tst.aggregate([{ "$group": { "_id": "$masterID", "pos": { "$max": "$pos" } } }])
示例对象是:
> db.tst.find()
{ "_id" : ObjectId("547d6bd28e47d05a9a492e2e"), "masterID" : "master", "pos" : "453", "id" : "hallo" }
{ "_id" : ObjectId("547d6bda8e47d05a9a492e2f"), "masterID" : "master", "pos" : "147", "id" : "welt" }
{ "_id" : ObjectId("547d6be68e47d05a9a492e30"), "masterID" : "master2", "pos" : "1", "id" : "welt" }
想要的聚合结果是:
{ "_id" : ObjectId("547d6bd28e47d05a9a492e2e"), "masterID" : "master", "pos" : "453", "id" : "hallo" }
{ "_id" : ObjectId("547d6be68e47d05a9a492e30"), "masterID" : "master2", "pos" : "1", "id" : "welt" }
有没有办法通过聚合来实现这个结果,还是我需要使用$push来获取所有分组的对象并在Java代码中围绕聚合实现pos的最大化?
这个问题mongodb aggregation: How to return a the object with min/max instead of the value 表明$first 或$last 应该用于按pos 排序的对象,但我看不到它如何返回整个对象。
【问题讨论】:
标签: mongodb aggregation-framework