开发者

In the MongoDB java driver, how do I pass a key function ('keyf') to a 'group' command

开发者 https://www.devze.com 2023-04-12 04:17 出处:网络
I would like to be 开发者_开发百科able to use the mongodb group command with the \'keyf\' parameter through the java driver. Has anyone been successful with this?You have to use the deprecated method

I would like to be 开发者_开发百科able to use the mongodb group command with the 'keyf' parameter through the java driver. Has anyone been successful with this?


You have to use the deprecated method DBCollection.group(DBObject args) and add the key function javascript code as a string under the DBObject key named "$keyf".

BasicDBObject args  = new BasicDBObject();
args.put("ns", nameSpace);
args.put( "initial" , initialDBObject );
args.put( "cond" , queryDBObject );
args.put( "$reduce" , reduceJavasriptCodeString );
args.put("$keyf", keyfJavascriptCodeString );
if( finalize != null ) args.put("finalize", finalizeJavascriptCodeString );
DBObject groupResult = mydbCollection.group(args);


This piece of code should do the work for you:

public static CommandResult exeMapReduceAlikeGroupCmd(DB db, String colName, String keyFunc, DBObject query,
                                                      String reduceFunc, DBObject initial) {
    BasicDBObject cmd = new BasicDBObject("ns", colName);// this is the collection name
    cmd.append("$keyf", keyFunc);// keyf function
    cmd.append("cond", query); // cond query object
    cmd.append("$reduce", reduceFunc);// reduce function
    cmd.append("initial", initial);// initial value
    cmd = new BasicDBObject("group", cmd);
    return db.command(cmd, db.getOptions());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号