0

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
  • It seems like getNextSequence is a function written in the mongo javascript shell. Neither the database (mongod) nor the Java side knows this function exists and neither is able to interprete the Javascript code the function contains. You will have to reimplement it in Java. Commented Dec 6, 2014 at 15:47

2 Answers 2

0

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.

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

Comments

0

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.

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.