Call stored function mongodb java driver - java

I have a problem executing stored function on MongoDB from my java code , i have a stored function like this.
db.system.js.save({
_id:"myFunction",
value:function(data){
//todo
return 1 + 1;
}
});
And in my java code :
mongoClient = new MongoClient(SERVER, PORT); // should use this always
db = mongoClient.getDB(DB);
DBObject datos = new BasicDBObject();
datos.put("val", "myvalue");
Then i am trying to execute the function:
try 1
db.doEval("myFunction", datos);
try 2
db.eval("myFunction", datos);
try 3
DBObject query = new BasicDBObject();
query.put("myFunction", datos);
db.command(query);
But the stored function does not execute, any ideas ?

I solved, it seems to pass values/objects to the stored function you have to serialize the object as JSON, so I did this :
String values = JSON.serialize(datos);
Then my java code looks like :
CommandResult er = db.doEval("myFunction("+values+")");
And the stored function gets executed correctly.

Related

Why the aggregate function does not give the desired result?

Was trying to change the data type of all values in a specific field, without use of iterators.
Here tid is the field name
I tried running the code in Mongo using
var ch ={"$addFields" : { "tid" : { "$convert":{"input":"$tid" , "to" : 2}}}}
db.test.aggregate(ch);
Where test is my collection
Java Code :
BasicDBObject fieldObject = new BasicDBObject();
fieldObject.put("$convert",new BasicDBObject().append("input",
"$tid").append("to", 2));
BasicDBObject addField = new BasicDBObject("$addFields",new
BasicDBObject("tid",fieldObject));
System.out.println(addField);
List<BasicDBObject> options = new ArrayList<>();
options.add(addField);
details.aggregate(options);
When I ran the code in mongo command line, the data types are changing from Integer to String.
But no change when I run the same through java code. Is there any issue with my Java Code.

OraclePreparedStatementWrapper cannot be cast to java.sql.CallableStatement

I'm trying to call oracle db function by java as following :
StoredProcedureCall getTaxProcedureCall = new StoredProcedureCall();
getTaxProcedureCall.setProcedureName("getTaxByCustomerId");
getTaxProcedureCall.addNamedArgument("ImpactedParty");
getTaxProcedureCall.addNamedArgument("ImpactedPartyType");
getTaxProcedureCall.addNamedOutputArgument("P_TAX");
getTaxProcedureCall.addNamedOutputArgument("A_TAX");
DataReadQuery query = new DataReadQuery();
query.setCall(getTaxProcedureCall);
query.addArgument("ImpactedParty");
query.addArgument("ImpactedPartyType");
Vector queryValues = new Vector();
queryValues.add(cusId);
queryValues.add("CSID");
Vector<DatabaseRecord> records = (Vector<DatabaseRecord>)TransactionContext.getCurrent().getUnitOfWork().executeQuery(query, queryValues);
return records;
but when run it, it gave : oracle.jdbc.driver.OraclePreparedStatementWrapper cannot be cast
to java.sql.CallableStatement
at Vector<DatabaseRecord> records = (Vector<DatabaseRecord>)TransactionContext.getCurrent().getUnitOfWork().executeQuery(query, queryValues);
I have solved the issue by replacing StoredProcedureCall with SQLCall
and pass sql string like:
SELECT getTaxByCustomerId(#ImpactedParty, #ImpactedPartyType, #TaxProfile) AS P_TAX FROM DUAL
now it's work fine.

Powerbuild Dateobject to java

i am doing a task converting VB script written from Powerbuild to java,
i am struggled at converting the DataStore Object into java ,
i have something like this :
lds_appeal_application = Create DataStore
lds_appeal_application.DataObject = "ds_appeal_application_report"
lds_appeal_application.SetTransObject(SQLCA)
ll_row = lds_appeal_application.retrieve(as_ksdyh, adt_start_date, adt_end_date, as_exam_name, as_subject_code)
for ll_rc = 1 to ll_row
ldt_update_date = lds_appeal_application.GetItemDatetime(ll_rc, "sqsj")
ls_caseno = trim(lds_appeal_application.GetItemString(ll_rc, "caseno"))
ls_candidate_no = trim(lds_appeal_application.GetItemString(ll_rc, "zkzh"))
ls_subjectcode = trim(lds_appeal_application.GetItemString(ll_rc, "kmcode"))
ls_papercode = trim(lds_appeal_application.GetItemString(ll_rc, "papercode"))
ls_name = trim(lds_appeal_application.GetItemString(ll_rc, "mc"))
ll_ksh = lds_appeal_application.GetItemDecimal(ll_rc, "ks_h")
ll_kmh = lds_appeal_application.GetItemDecimal(ll_rc, "km_h")
simply speaking, a datasoure is created and a data table is point to it by sql query(ds_appeal_application_report). Finally using a for loop to retrieve information from the table.
in java way of doing, i use an entities manager to createnativequery and the query can result a list of object array. However, i just dont know how to retrieve the information like VB using the DataStore Object.
please give me some advice . Thanks

get some attributes from mongodb except one or two

I would like to get some information which is in a mongoDB except some attributes.
I tried it in cmd and it worked:
db.orders.find({name:"chabeee"},{_id:0, name:1, worksAt:1})
Then I get this result:
{ "name" : "chabeee", "worksAt" : "jobAtBp" }
{ "name" : "chabeee", "worksAt" : "jobAtRE" }
Its okay, but I want to get in a Java Program. How can I do that?
You have to create one additional BasicDBObject, which will be used for pointing out which exact keys to be fetched. And finally the DBCollection#find(DBObject ref, DBObject keys) method has to be invoked in order to pass the desired projection keys.
BasicDBObject query = new BasicDBObject("name", "chabeee");
BasicDBObject keys = new BasicDBObject();
keys.put("_id", 0);
keys.put("name", 1);
keys.put("worksAt", 1);
BasicDBCursor result = collection.find(query, keys);
Then you just have to iterate over the BasicDBCursor and verify the result.
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

Updating mongodb with java driver takes forever?

So this is the case: I have a program that takes two large csv-files, finds the diffs and then sends a array list to a method that is supposed to update the mongodb with the lines from the array. The problem is the updates are taking forever. A test case with 5000 updates takes 36 minutes. Is this normal?
the update(List<String> changes)-method something like this:
mongoClient = new MongoClient(ip);
db = mongoClient.getDB("foo");
collection = db.getCollection("bar");
//for each line of change
for (String s : changes) {
//splits the csv-lines on ;
String[] fields = s.split(";");
//identifies wich document in the database to be updated
long id = Long.parseLong(fields[0]);
BasicDBObject sq = new BasicDBObject().append("organizationNumber",id);
//creates a new unit-object, that is converted to JSON and then inserted into the database.
Unit u = new Unit(fields);
Gson gson = new Gson();
String jsonObj = gson.toJson(u);
DBObject objectToUpdate = collection.findOne(sq);
DBObject newObject = (DBObject) JSON.parse(jsonObj);
if(objectToUpdate != null){
objectToUpdate.putAll(newObject);
collection.save(objectToUpdate);
}
That's because you are taking extra steps to update.
You don't need to parse JSONs manually and you don't have to do the query-then-update when you can just do an update with a "where" clause in a single step.
Something like this:
BasicDBObject query= new BasicDBObject().append("organizationNumber",id);
Unit unit = new Unit(fields);
BasicDBObject unitDB= new BasicDBObject().append("someField",unit.getSomeField()).append("otherField",unit.getOtherField());
collection.update(query,unitDB);
Where query specifies the "where" clause and unitDB specifies the fields that need to be updated.

Categories