DB.eval() with Mongo Java Driver

非 Y 不嫁゛ 提交于 2019-12-12 17:09:37

问题


I've prepared some script to execute on Mongo. It works as expected from command line:

mongo 127.0.0.1:27017/dbName script.js

But when I tried to move it in java (scala) code it doesn't work with

db.eval(scriptContent)

Does anybody succeed with DB.eval() method?


回答1:


Question #1: Why does it need to be in Java? Can you just schedule the mongo ... command above to run via cron?

Question #2: Is it possible to implement via the Java driver instead?

The Java driver can execute Map / Reduce commands. You'll have to copy the javascript text into your Java code somewhere, but if you're working from the driver it can all be done there.

In fact one of the ideas behind the drivers is that they are just issuing DB commands like the shell. So you should be able to do everything from the shell OR from Java.




回答2:


eval() VS running the script like this

mongo 127.0.0.1:27017/dbName script.js

are not equivalent. eval() sends the script to be executed on a mongod instance, whereas the command uses the driver to access the db.

As pointed out by others, eval() should be avoided as it has a lot of drawbacks, for instance, won't work on a sharded environment, or does not allow to create indexes in background.

Oh! and to answer the question, yes I did succeed with eval() in java. However, there are things that will simply not work ;)



来源:https://stackoverflow.com/questions/11781824/db-eval-with-mongo-java-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!