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
});
1
  • 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. Commented Apr 26, 2013 at 15:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.