目前我正在研究JAVA中的一个项目,我需要通过JAVA运行Javascript Mongo查询,我想我可以在java中使用db.eval()做类似的事情。问题是我对Mongo有以下Javascript查询,我不知道如何将整个脚本传递给db.eval()方法。任何的想法 ?请告诉我。 谢谢
var red = function(doc, out) {
out.count_order++;
out.sum_qty += doc.quantity;
out.sum_base_price += doc.extendedprice;
out.sum_disc_price += doc.extendedprice * (1 - doc.discount);
out.sum_charge += doc.extendedprice * (1 - doc.discount) * (1 + doc.tax);
out.avg_disc += doc.discount
};
var avg = function(out) {
out.avg_qty = out.sum_qty / out.count_order;
out.avg_price = out.sum_base_price / out.count_order;
out.avg_disc = out.avg_disc / out.count_order
};
db.deals.group( {
key : { RETURNFLAG : true, LINESTATUS : true},
cond : { "SHIPDATE" : {$lte: new Date(1998, 8, 1)}},
initial: { count_order : 0, sum_qty : 0, sum_base_price : 0, sum_disc_price : 0,
sum_charge : 0, avg_disc : 0},
reduce : red,
finalize : avg
});
答案 0 :(得分:0)
看起来你正在尝试做mapreduce和Java驱动程序抽象处理并使事情变得复杂,但我认为你的问题的核心是如何1)存储js函数和2)用Java运行它们
我将首先通过一个例子(我修改你的函数返回" out"因为我认为否则需要对驱动程序的mapreduce操作进行不同的处理):
String fnc = "function(doc, out) {" +
"out.count_order++;"+
"out.sum_qty += doc.quantity;"+
"out.sum_base_price += doc.extendedprice;"+
"out.sum_disc_price += doc.extendedprice * (1 - doc.discount);"+
"out.sum_charge += doc.extendedprice * (1 - doc.discount) * (1 + doc.tax);"+
"out.avg_disc += doc.discount; "+
"return out;" +
"};";
BasicDBObject doc = BasicDBObject("_id","doc");
BasicDBObject out = BasicDBObject("_id","out");
System.out.println(
(new MongoClient()).getDB('test').eval(fnc,doc,out)
);
WRT 1)(保存功能)...您可以在集合中保存服务器中的功能。但我还没有能够让Java驱动程序找到它们。在mongoshell中,您可以执行此操作(此示例来自Call stored function in mongodb):
system.js.save({
_id: "echoFunction",
value: function (x) {
return 'echo: ' + x;
}
})
使用
在shell中运行它db.eval("echoFunction('test')")