How to group by count in morphia?

2.2k views Asked by At

I have a collection:

public class Message {
    @Id
    ObjectId id;
    String group;
}

I need to count number of messages per each group. Is it possible to avoid iterating through entire collection?

2

There are 2 answers

0
Stepan Yakovenko On BEST ANSWER

Here in this working example, MessageEntry stands for Message and linf stands for group:

    DBCollection myColl = ds.getCollection(MessageEntry.class);
    DBObject key = new BasicDBObject("linf",true);
    DBObject initial = new BasicDBObject("cnt",true);
    String reduce = "function(item,prev){prev.cnt+=1;}";

    DBObject group = myColl.group(key, null, initial, reduce);

    HashMap<String,Long> ret = new HashMap();
    for(String k:group.keySet()){
        BasicDBObject l = (BasicDBObject) group.get(k);
        DBRef dbRef = (DBRef) l.get("linf");
        Linf linf = ds.get(Linf.class,dbRef.getId() );
        Double cnt = (Double) l.get("cnt");
        ret.put(linf.limad,cnt.longValue());
    }
    return ret;
1
evanchooly On

The query language in mongo, and thus morphia, doesn't really support that. The aggregation framework does, however, which is the good news. The (almost)n bad news is that morphia doesn't (yet) support aggregations. I actually have support built on a branch but it's dependent on the 2.12 release of the java driver. Here is the issue tracking this feature: https://github.com/mongodb/morphia/issues/449