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 ?
解决方案
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.