Java 实现MongoDB Group 操作

在Java For  MongoDB 中时通过 DBCollectino对象的group 方法来实现Group 操作。 
 

官方IPA:http://api.mongodb.org/java/2.7.3/

方法解释:

group

public DBObject group(DBObject key,
                      DBObject cond,
                      DBObject initial,
                      String reduce,
                      String finalize)
               throws MongoException
Applies a group operation

Parameters:
key - - { a : true }
cond - - optional condition on query
reduce - javascript reduce function
initial - initial value for first match on a key
finalize - An optional function that can operate on the result(s) of the reduce function.
Returns:
Throws:
MongoException
See Also:
http://www.mongodb.org/display/DOCS/Aggregation


案例实现:

final List<String> targetTerms = Arrays.asList("dogs", "cats");
final Datastore ds = ….
final DBCollection coll = ds.getCollection(Example.class);
BasicDBObject key = new BasicDBObject("_id", true);
BasicDBObject cond = new BasicDBObject();
cond.append("indices", new BasicDBObject("$in", targetTerms));
BasicDBObject initial = new BasicDBObject();
initial.append("score", 0);
initial.append("targetTerms", targetTerms);
String reduce = "function (obj, prev) { " +
        "  for (i in prev.targetTerms) {" +
        "    targetTerm = prev.targetTerms[i];"+
        "      for (j in obj.indices) {" +
        "        var index = obj.indices[j];"+
        "        if (targetTerm === index) prev.score++;" +
        "    }" +
        "  }" +
        "}";
String fn = null;
final BasicDBList group = (BasicDBList) coll.group(key, cond, initial, reduce, fn);


你可能感兴趣的:(JavaScript,java,mongodb,function,String)