Call js server on mongodb from java

I like to run equvilant mongodb shell script from java

Mongolian shell script:

db.users.insert( { _id: getNextSequence("userid"), name: "Sarah C." } ) 

I tried something like this in java and it didn't work.

 BasicDBObject krUserRecord = new BasicDBObject("_id", getNextSequence("userid")) .append("name", "Sarah C"); 

Can anyone help?

0
source share
2 answers

As Kivank said, getNextSequence is actually a javascript function. This is just a wrapper around findAndModify, as described in mongo here . Essentially, you will need to create a document containing the counter that you want to increase. Use findAndModify to increase it so that you get transactional behavior. If you intend to do this in Java, you need to make sure your document exists before you start issuing findAndModify. This is best done by encapsulating the findAndModify logic in a single class so that you can handle initialization normally.

0
source

It is not easy to execute Mongo JS in the JDK because the original client has a JS library that wraps command calls to provide pretty syntax. The Java driver does the same job to provide an easy-to-use Java API.

You can use the Jongo library, which is designed to write Java code, similar to how you do it in the mongo shell.

If you want to run jon mongo mongo, you can do this using SSH for the MongoDB host or host with the mongodb client installed. (Include the mongo client executable in the application - a bad idea that blocks you in a specific version of the database). Here is an example of a simple shell providing a function call via ssh.

0
source

All Articles