在java中调用mongodb上的服务器js函数 [英] Calling server js function on mongodb from java
问题描述
我喜欢从java运行mongodb shell脚本。
I like to run the equvilant of mongodb shell script from java
Mongo shell脚本是:
Mongo shell script is :
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
)
我在java中尝试过类似的东西,但没有成功。
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 ?
推荐答案
正如Kivanc所说,getNextSequence实际上是一个javascript函数。这只是findAndModify的一个包装,如mongo here 。基本上你需要创建一个文件来存放你想增加的计数器。使用findAndModify来增加它,以便获得类似事务的行为。如果你打算用Java来做到这一点,那么在开始发行findAndModify之前,你需要确保你的文档已经存在。最好是将findAndModify逻辑封装在一个类中,这样你就可以正确处理初始化。
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.
这篇关于在java中调用mongodb上的服务器js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!