Reputation: 511
I am using below query to fetch data from mongo-db:
db.FetchedUrl.aggregate({
"$match": {
"type": db.eval('echoFunction(\"news\")')
}
})
This is my stored function:
db.system.js.save({
_id: "echoFunction",
"value": function(x){return x}
})
This code is working fine at mongo-db shell. How to write equivalent Java code to call stored function in aggregation?
Upvotes: 0
Views: 1169
Reputation: 151122
I think you need to understand what is actually happening here. Take this for an example, and you can do it yourself in the shell. So declare a variable there like this:
var param = db.eval('echoFunction(\"news\")');
And then do the aggregate again like this:
db.FetchedUrl.aggregate({
"$match": {
"type": param
}
})
Here is the thing. You know you don't have a "stored" variable on your server called "param" but of course the result is the same as what you did before.
This is because, much as the same as what you have done, this value gets evaluated in the "shell" before the request is sent to the server.
So in this case, your "server side" function is not providing any server side evaluation at the time of the aggregate being performed.
What this means is that any "Java" code you write is going to be pre-evaluated into the BSON document that is sent before it is sent to the server.
So whatever means you are using to "fetch" this value, then you need to write that in "Java" code. That value is then placed in as the value to the same key in a BSON document by the methods your driver supplies.
There are some notes on aggregation with the Java driver on the MongoDB website.
Upvotes: 1