0

currently I'm working on a project in Java, and I need to run the JavaScript Mongo queries using Java. I figured out I can do something like that using db.eval(). Problem is I have the following JavaScript query for Mongo and I have no idea how can I pass the whole script to the db.eval() method.

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
});
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
diba6122
  • 31
  • 1
  • 7
  • I haven't worked with MongoDB but I guess you can put this `String` in a `StringBuilder` and send it to your `db.eval()` method. – Luiggi Mendoza Apr 26 '13 at 15:54

2 Answers2

1

I encourage you to look at the mongodb java driver to run queries from Java. The Java driver allows one to interact with their mongodb database directly in Java. Thus, you can just port this code to Java and do it all in Java, avoiding ever having to use javascript or db.eval. Let me know if you would like more clarification.

ACE
  • 486
  • 3
  • 6
0

you can also use stored procedures in which you can call the stored functions from the java-driver using eval()

Some details : http://dirolf.com/2010/04/05/stored-javascript-in-mongodb-and-pymongo.html

Recently in v2.4 there were some concurrency improvements for javascript operations : http://docs.mongodb.org/manual/release-notes/2.4-javascript/

Abhishek Kumar
  • 3,328
  • 2
  • 18
  • 31