我希望能够通过java驱动程序使用带有'keyf'参数的mongodb group命令。有没有人成功过这个?
答案 0 :(得分:4)
您必须使用不推荐使用的方法DBCollection.group(DBObject args)并将键函数javascript代码添加为名为“$ keyf”的DBObject键下的字符串。
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);
答案 1 :(得分:1)
这段代码应该为您完成工作:
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());
}