问题
I like to run the equvilant of mongodb shell script from java
Mongo shell script is :
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
)
I've tried something like this in java, which did not work .
BasicDBObject krUserRecord = new BasicDBObject("_id", getNextSequence("userid"))
.append("name", "Sarah C");
Can anyone help ?
回答1:
As Kivanc said, getNextSequence is actually a javascript function. It's just a wrapper around findAndModify as documented by mongo here. Essentially you'll need to create a document that holds the counter that you want to increment. Use findAndModify to increment it so that you're getting transaction-like behavior. If you're going to do that in Java, you need to make sure that your document exists before you start issuing findAndModify. It's best to do that by encapsulating the findAndModify logic in a class all by itself so you can handle initialization properly.
回答2:
It is not so easy to execute Mongo JS in JDK, because original client has JS library that wraps command calls to provide pretty syntax. Java driver do the same work to provide easy to use java API.
You may use Jongo library, that aims to write java code similar to how you do it in mongo shell.
If you want to execute any mongo JS by java you can do it with SSH to MongoDB host or host with mongodb client installed. (Include mongo client executable in application - bad idea that locks you on specific database version). Here example of simplest wrapper that provide function calling thru ssh.
来源:https://stackoverflow.com/questions/27332979/calling-server-js-function-on-mongodb-from-java